如何使用optgroups laravel在多选下拉列表中将所选项目标记为选中


How to mark select items as checked in a multiselect dropdown with optgroups laravel

我正在使用这个选择下拉插件。在存储方法期间,我可以在下拉列表中获取所选项目的所有ID。然而,在编辑方法期间,当我试图加载具有多个值的实体时,我无法在下拉列表中将项目标记为选中。

假设我正在与学校合作,每个学校都可以属于许多类别,所以在联系人和类别之间有一个belongsToMany关系。在选择下拉列表创建表单上,我的类别根据它们所属的类型分组在optgroup中…我在类型和类别之间有一个oneToMany关系。。。下面是我在创建表单上的代码片段…

<select class="form-control select-picker" name="categories[]" multiple="multiple" title="Choose one or more">
   @foreach ($types as $type)
   <optgroup label="{{ $type->name}}">
     <?php $type_categories = $type->categories;?>
        @foreach ($type_categories as $category)
        <option value="{{ $category->id }}">{{ $category->name }}</option>
        @endforeach
   </optgroup>
   @endforeach

现在,我如何在编辑模式下填充下拉列表,同时标记所选值以删除optgroup,因为如果我省略optgroup ,下面的代码会起作用

{{ Form::select('categories[]', App::make('Category')->lists('name', 'id'), $school->categories()->select('categories.id AS id')->lists('id'),['class' => 'form-control select-picker','multiple'])}}

您可以为此使用自定义Form扩展:

Form::macro('categoriesSelect', function ($name, $types, $selected, $attributes) 
{
    $groups = [];
    foreach ($types as $type)
    {
        $groups[$type->name] = $type->categories->lists('name', 'id');
    }
    return Form::select($name, $groups, $selected, $attributes);
});

则仅向CCD_ 2的集合提供Categories:

Form::categoriesSelect(
  'categories[]',
  App::make('Type')->with('categories')->get(),
  $school->categories()->select('categories.id AS id')->lists('id'),
  ['class' => 'form-control select-picker','multiple']
)

注意:我不会在blade模板中调用这些查询,但这是另一回事。