簡體   English   中英

如何在laravel中預選多個select 8

[英]How to preselect multiple select in laravel 8

我正在嘗試從 select 選項存儲多個 select 值,我能夠保存但是當我從數據庫中獲取數據時,它在 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)

刀片文件:

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

子類別列表.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

如圖select value是對的,data-select-value是錯誤的

在此處輸入圖像描述

您可以將其作為數組並使用in_array function 進行檢查

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

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

當我們將parent_id轉換為數組並檢查id是否已經在其中時

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM