laravel admin 多选默认值是有bug的,找了很多资料,最后得以解决. 文件位置:
D:\WWW\xxxx\vendor\encore\laravel-admin\src\Form\Field\Select.php
public function load($field, $sourceUrl, $idField = 'id', $textField = 'text', bool $allowClear = true)
{
if (Str::contains($field, '.')) {
$field = $this->formatName($field);
$class = str_replace(['[', ']'], '_', $field);
} else {
$class = $field;
}
$placeholder = json_encode([
'id' => '',
'text' => trans('admin.choose'),
]);
$strAllowClear = var_export($allowClear, true);
$script = <<<EOT
$(document).off('change', "{$this->getElementClassSelector()}");
$(document).on('change', "{$this->getElementClassSelector()}", function () {
var target = $(this).closest('.fields-group').find(".$class");
$.get("$sourceUrl",{q : this.value}, function (data) {
target.find("option").remove();
$(target).select2({
placeholder: $placeholder,
allowClear: $strAllowClear,
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
});
if (target.data('value')) {
$(target).val(target.data('value').split(','));// 这里需要分解存储的值为数组才能支持多选
}
$(target).trigger('change');
});
});
$("{$this->getElementClassSelector()}").trigger('change'); // 加上这一行才可以支持自动加载所有的可选值
EOT;
Admin::script($script);
return $this;
}
|