今天在開發公司一個功能時,公司開發環境用的是laravel-admin,因爲需要用上select聯動,所以根據文檔說明進行開發,併成功的使用上了,代碼我就不重複,大家可以去參考laravel-admin官網的說明。
首先我們找到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');
作用就是在初始化的時候觸發一次聯動。
然後在我們的表單中,我們再來定義編輯初始時候的值,代碼如下:
$form->select('hezuo', "合作模式")->options(function () {
$record = request()->route()->parameters();
$record = $record["chanpin"];
$data = ChanpinModel::where('id', $record)->first();
$hezuoList = array(
"1" => '測試1',
"2" => '測試2',
"3" => '測試3',
);
$hezuo = $data->hezuo;
return [$hezuo => $hezuoList[$hezuo]];
});
這段代碼是根據當前記錄的值,去獲取對應所屬那個選項,這樣便使select聯動編輯時,能夠默認選上我們的值。