奥丁9
奥丁9
后端
数据库
redis
mysql
mongoDB
达梦
php
laravel
laravel-admin
dcat
表单
表格
java
spring
python
go
c
c++
前端
vue
nodejs
sass/less
html/css
前端框架
javascript
微信生态
公众号
小程序
uniapp
typescript
其他
AI
数据结构
安全
linux
seo
git
健身
算法
正则表达式
docker
待分类
后端
/
php
/
laravel
/
dcat
dcat的multipleSelect多选下拉增加自定义选项
1年前
aoding9
49
php
laravel
dcat
有这样一个需求,文章设置标签,默认的多选下拉只能选择已有的标签,我希望能够追加自定义标签  假如我要追加一个php123的tag,但是只有php而没有php123  先输入php123然后回车即可  代码如下: ``` class FormService { public function enterNewMultipleSelectOption() { \Admin::script( <<<JS $('select').select2().on('select2:open', function() { // console.log($(this).val()) // set a global reference for the current selected Select // console.log('found this ---> '+$(this).attr('id')); if (typeof tempSelectedObj === 'undefined') { tempSelectedObj = null; } tempSelectedObj = this; }); $(document).on('keyup','input.select2-search__field',function (e) { // capture the return event if (e.keyCode === 13) { var newValue = $(this).val(); // 如果已经有了就不添加 if(newValue===''){ return; } var oldVal=$(tempSelectedObj) .val(); // create new option element var newOpt = $('<option>') .val(newValue) .text(newValue); // append to the current Select $(tempSelectedObj) .append(newOpt); oldVal.push(newValue) $(tempSelectedObj) .val(oldVal) .select2('close'); } }) JS ); } } ``` form中使用 ``` app(FormService::class)->enterNewMultipleSelectOption(); // 启用回车创建选项的功能 $form->multipleSelect('tags') ->customFormat(function($v) { if (!$v) return []; return array_column($v, 'id'); }) ->options(Tag::selectOptions()) // 已有的tag选项 ->saving(function($tags) { foreach ($tags as $k => $item) { if (!is_numeric($item) && !$tag = Tag::where('name', $item)->first()) { // 如果不是纯数字。并且name查不到就创建tag $tag = Tag::create(['name' => $item, 'count' => 1]); $tags[$k] = $tag->id; // id替换掉tag name } } return $tags; })->help('名称不能为纯数字,会混淆tag的id'); ``` 由于我是直接把php123这个tag name直接提交,而不是提交id,所以不能输入纯数字的tag,否则会被当做id,如果希望使用纯数字tag,可以在前端使用ajax即时创建tag返回id,然后把id追加进去,或者前端判断追加纯数字的时候,给name加前缀,然后再单独处理一下,我的
本作品采用
《CC 协议》
,转载必须注明作者和本文链接