$form->select('product_category_id','産品類别')->options(ProductCategory::where('parent_id',0)->pluck('title','id'))->load('product_category_er_id', '/admin/product_category_er');
$form->select('product_category_er_id','産品下一級類别');
public function product_category_er(){
$id=request('q');
return ProductCategory::where('parent_id',$id)->get(['id', DB::raw('title as text')]);
}
此處應該寫為下面的:
return ProductCategory::where('parent_id','=', $parent_id)->get(['id', DB::raw('title as text')]);
不應寫為:
return ProductCategory::where('parent_id','=', $parent_id)->pluck('title ', 'id');
laravel-admin解決表單SELECT關聯時,編輯預設沒選上
首先我們找到select的js,路徑:跟目錄/vendor/encore/laravel-admin/src/Form/Field下的Select.php檔案,找到下面代碼:
$script = <<<EOT
$(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({
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
}).trigger('change');
});
});
EOT;
并修改成以下代碼:
$script = <<<EOT
$(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({
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
}).trigger('change');
});
});
$('{$this->getElementClassSelector()}').trigger('change');
EOT;
我們在原有代碼中加入這句:
$('{$this->getElementClassSelector()}').trigger('change');