【问题标题】:How to preselect multiple select in laravel 8如何在 laravel 8 中预选多项选择
【发布时间】:2021-08-16 19:19:40
【问题描述】:

我正在尝试从选择选项中存储多选值,我可以保存,但是当我从数据库中获取数据时,它在选择中选择了错误的选项;

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

如图选择值正确但数据选择值错误

【问题讨论】:

  • $products-&gt;parent_id 应该给什么?
  • 列出特定产品的位置

标签: php laravel laravel-8


【解决方案1】:

您可以将其设为数组并使用in_array 函数进行检查

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

@if(in_array($category-&gt;id, explode(',',$products-&gt;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

【讨论】:

  • in_array() 期望参数 2 是数组,int 给定
  • 哦,对不起,我把数组作为第一个参数,但它应该是第二个参数
  • 好的,但是有一个问题我只得到了选择的类别而不是子类别。正如您在图片中看到的 --suraj si 是 book 的孩子,并且 --hindi 是 suraj 的孩子
  • 更新问题
  • 终于解决了子类的问题。感谢@Mahmoud Gamal 的帮助
猜你喜欢
  • 2021-07-19
  • 2021-12-15
  • 2021-07-25
  • 2021-06-22
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
相关资源
最近更新 更多