laravel-admin 省市區 三級 選擇 select2 selected 無效問題解決方案


本來寫好的省市區 三級聯動好好的 composer update 一下 好像突然不管用了 於是只能 重新找解決方案 和 研究源碼去了 

(和我使用相同方法並正在尋找解決辦法的朋友可以直接看最后)

這里我使用的是 load 方式加載的三級聯動 

Controller文件

use Illuminate\Http\Request;
use Encore\Admin\Layout\Content;
 
    // 編輯方法
    public function edit($id, Content $content)
    {        
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form(true, $id)->edit($id));
     }

    //form
    protected function form($isEditing = false, $id = false)
    {
        $form = new Form(new xxxxx());

        if ($id) {
            $model = xxxxx::find($id);
        }

        // 修改地址
        if ($isEditing && $model->province) {

            $form->select('province', '省')->options('/admin/api/province/'.$model->province)->load('city', '/admin/api/city/'.$model->city)->required();

            $form->select('city', '市')->options(function($id){
                return Province::where('id' , $id)->pluck('name' , 'id');
            })->load('area', '/admin/api/area/'.$model->area)->required();

            $form->select('area', '區縣')->options(function($id){
                return Province::where('id' , $id)->pluck('name' , 'id');
            })->required();

        } else {

            $form->select('province', '省')->options(
                Province::where(['city'=>0])->pluck('name', 'id')
            )->load('city', '/admin/api/city')->required();

            $form->select('city', '市')->load('area', '/admin/api/area')->required();

            $form->select('area', '區縣')->required();
        }

    }

api方法

    public function getProvince($id = false,Request $request)
    {
        $province = Province::where(['city'=>0])->get(['id', 'name AS text']);  
        if ($id) {
            foreach ($province as $key) {
                if ($key->id == $id) {
                    $key->selected = true; 
                }
            }
        }
        return $province;
    }

 

api數據返回格式

[{
    "id": 781,
    "text": "黃浦區"
}, {
    "id": 782,
    "text": "徐匯區",
  // 原本默認選中 增加 selected true就可以了 "selected": true }, { "id": 783, "text": "長寧區" }]

select2 手冊地址:https://select2.org/programmatic-control/add-select-clear-items

本來在返回數據中 增加 

    selected : true

就可以默認選擇的不知道為什么突然不行了 找了一下網上的幾種解決方式 試了一下都不太好用不過提供了一些解決思路

去翻閱 select2 的手冊的時候發現了 可以使用 來動態設置默認值

$('#mySelect2').val(['1', '2']);

$('#mySelect2').trigger('change');

於是就去 vendor\encore\laravel-admin\src\Form\Field\Select.php

里面調試了起來 感覺可能是 

province
city
area

這三個關鍵字影響了 因為在我接口里面返回的只有id 和 值 但是在插件生成的html 中 多了地區編號等數據 例如  data-value="782,310104,徐匯區,31,01,04,0"

<select class="form-control area select2-hidden-accessible" style="width: 100%;" name="area" required="1" data-value="782,310104,徐匯區,31,01,04,0" tabindex="-1" aria-hidden="true">
    <option value="781">黃浦區</option>
    <option value="782">徐匯區</option>
    <option value="783">長寧區</option>
    <option value="784">靜安區</option>
</select>

 

在vendor\encore\laravel-admin\src\Form\Field\Select.php 文件的 load() 方法中 console.log() 的時候 發現 

$(target).val(target.data('value')); 里面 target.data('value') 的值是  "782,310104,徐匯區,31,01,04,0" 這明顯是和我數據的值是對不上的 於是強行獲取並修改了下 load方法

    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");
    // 修改后新增代碼
    var selected_value = null;
    $.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;
                // 修改后新增代碼
                if (d.selected) {
                    selected_value = d.id;
                }
                return d;
            })
        });
        if (target.data('value')) {
            // 源代碼
            // $(target).val(target.data('value'));
            // 修改后新增代碼
            $(target).val(selected_value);
        }
        $(target).trigger('change');
    });
});
EOT;

        Admin::script($script);

        return $this;
    }

 

在頁面試了下 問題順利解決 如果有其他解決辦法歡迎分享 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM