【问题标题】:How to mark select items as checked in a multiselect dropdown with optgroups laravel如何使用 optgroups laravel 在多选下拉列表中将所选项目标记为已选中
【发布时间】:2014-09-06 07:48:49
【问题描述】:

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

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

<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'])}}

【问题讨论】:

    标签: php select laravel laravel-4 multi-select


    【解决方案1】:

    您可以为此使用自定义 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']
    )
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多