简体   繁体   中英

How to preselect multiple select in laravel 8

I am trying to store multi select value from select option, I am able to save but when I fetch the data from the database, then It is selecting wrong options in select;

category = [{'id' : "1", 'name'=>'A'},{'id' : "2", 'name'=>'B'},{'id' : "3", 'name'=>'C'},{'id' : "4", 'name'=>'D'},{'id' : "5", 'name'=>'E'}]
parent_category = [1,2,3](comming from database)

Blade File:

<select class="js-example-basic-multiple" id="category" name="parent_id[]" multiple>
   <option value=0>None</option>
       @if($categories)
          @foreach($categories as $category)
              <?php $dash=''; ?>
              <option value="{{$category->id}}" @if(in_array($category->id, explode(',',$products->parent_id))) selected @endif>{{$category->name}}</option>
               @if(count($category->subcategory))
                   @include('pages.admin.category.sub-category-list',['subcategories' => $category->subcategory,'products'=>$products])
                 @endif
          @endforeach
       @endif
</select>

sub-category-list.blade.php

<?php $dash.='-- '; ?>
@foreach($subcategories as $subcategory)
    <option value="{{$subcategory->id}} " @if(in_array($subcategory->id, explode(',',$products->parent_id))) selected @endif>{{$dash}}{{$subcategory->name}}</option>
       @if(count($subcategory->subcategory))
          @include('subCategoryList-option',['subcategories' => $subcategory->subcategory,'products'=>$products])
       @endif
@endforeach

As shown in the picture select value is right but data-select-value is wrong

在此处输入图像描述

You can make it as array and make check using in_array function

https://www.php.net/manual/en/function.in-array.php

@if(in_array($category->id, explode(',',$products->parent_id)) selected @endif

As we convert parent_id to array and make a check if id already in it

<select class="js-example-basic-multiple" id="category" name="parent_id[]" multiple>
   <option value=0>None</option>
   @if($categories)
      @foreach($categories as $category)
          <?php $dash=''; ?>
          <option value="{{$category->id}}" @if(in_array($category->id, explode(',',$products->parent_id)) selected @endif>{{$category->name}}</option>
           @if(count($category->subcategory))
               @include('pages.admin.category.sub-category-list',['subcategories' => $category->subcategory])
             @endif
      @endforeach
   @endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM