Laravel form builder multi select selected items

1.2k views Asked by At

Have an issue with showing selected items in multi select.

Have a 'filter.blade.php' sub view inside a 'index.blade.php' entity view

Sub view fragment, form input, one of several multi selects:

<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) }}

Controller action, which handle inputs from request to filter results

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,
    ]);
}

So, when the filter form is submitted to controller and the view with the variables like '_subcategories' is shown, should be selected ids from request in the multi select. But nothing selected.

http://joxi.ru/82QeLzDi135Xy2

It is strange and I stuck...

Thanks

1

There are 1 answers

0
Yuriy L. On BEST ANSWER

My working solution is:

stringifying each option value (ID in my case).

In html, instead of

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

<select>

should be something like

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

<select>

So, before passing an array with key-value pairs for form builder multi select, I added letter, for example, 'd' to value.

And, after form submitting with selected items, I clear every value and remove letter before handling this data