dcat的multipleSelect多选下拉增加自定义选项
有这样一个需求,文章设置标签,默认的多选下拉只能选择已有的标签,我希望能够追加自定义标签
假如我要追加一个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,可以提前创建好tag再用,也可以改动js部分,在按下回车事件中,用ajax即时创建tag返回id,然后把id追加进去,或者前端判断追加纯数字的时候,给name加前缀,然后后端匹配前缀单独处理
本作品采用《CC 协议》,转载必须注明作者和本文链接
:+1: