Laravel 表单生成器多 select selected 项

Laravel form builder multi select selected items

在多个 select 中显示 selected 项目时遇到问题。

在 'index.blade.php' 实体视图中有一个 'filter.blade.php' 子视图

子视图片段,表单输入,多个select之一:

<div class="col-lg-4 col-md-4 form-group">
    {!! Form::label('subcategories', trans('art-work.subcategory'), ['class' => 'control-label']) !!}
    {!! Form::select('subcategories[]', $subcategories, $_subcategories,
        [
            'id' => 'subcategories',
            'class' => 'form-control select2',
            'multiple' => 'multiple',
            'data-placeholder' => trans('crud.choose'),
    ]) !!}
</div>
....
{{ Log::info('subcategories', $_subcategories) }}

控制器操作,处理从请求到过滤结果的输入

public function filter(Request $request)
{
    $this->validate($request, $this->filterRules);
    $filters = [
        'category_id'     => (int) $request->category_id,
        'subcategories'   => $request->subcategories,
        'grades'          => $request->grades,
        'students'        => $request->students,
        'professors'      => $request->professors,
    ];

    $works = ArtWork::filtered($filters);
    $subcategories = Category::where('category_id', $filters['category_id'])
        ->get()
        ->pluck('title', 'id')
        ->toArray();

    return view('panel.art-work.index', [
        'works'           => $works,
        'subcategories'   => $subcategories,

        '_category'       => $filters['category_id'],
        '_subcategories'  => $filters['subcategories'],
        '_grades'         => $filters['grades'],
        '_students'       => $filters['students'],
        '_professors'     => $filters['professors'],

        '_filter'         => true,
    ]);
}

因此,当将过滤器表单提交给控制器并显示带有“_subcategories”等变量的视图时,应该select从多 select 中的请求编辑 ID。但没有 selected.

http://joxi.ru/82QeLzDi135Xy2

很奇怪,我卡住了...

谢谢

我的工作解决方案是:

将每个选项值(在我的例子中是 ID)串化。

在 html 中,而不是

<select>
   <option value="1">First</option>
   <option value="2">Second</option>
   ...
   <option value="n">Nth</option>

<select>

应该是这样的

<select>
       <option value="d1">First</option>
       <option value="d2">Second</option>
       ...
       <option value="dn">Nth</option>

<select>

因此,在为表单生成器 multi select 传递包含键值对的数组之前,我添加了字母,例如 'd' 到值。

并且,在提交带有 selected 项目的表单后,我在处理此数据之前清除每个值并删除字母