首页 文章

如何使用optgroups laravel在多选下拉列表中选中已选中的项目

提问于
浏览
0

我正在使用这个选择下拉插件 . 我可以在存储方法期间在下拉列表中获取所选项目的所有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'])}}

1 回答

  • 0

    您可以使用自定义 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);
    });
    

    然后只提供 TypesCategories 的集合:

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

    注意:我不会在刀片模板中调用这些查询,但这是另一个故事 .

相关问题