laravel 5.4 select2 multiple edit

时间:2017-04-14 09:14:31

标签: select2 laravel-5.4

我不知道如何填充编辑功能我的select2表单。这是我尝试这样做的。控制器:

public function edit($id)
{
    $company = Company::find($id);      

    $categories = MainCategory::all();
    $categories2 = array();
        foreach ($categories as $category) {
        $categories2[$category->main_cat_id] = $category->main_cat_name;
    }

    return view('company/edit_company')->with('company', $company)->with('categories', $categories2);
}

这是我的观点:

<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
<option value='{{$category->main_cat_id}}'>{{$category->main_cat_name}}</option>
</select>

这是我的JS:

<script type="text/javascript">
$('.select2-multi').select2();
$('.select2-multi').select2().val({!! json_encode($company->maincategories()->allRelatedIds()) !!}).trigger('change');
</script>

1 个答案:

答案 0 :(得分:2)

如果您的类别数据正确地显示在您的视图中;这似乎是代码中的一个数组。您可以在select元素中 foreach

<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
  @foreach($category as $category_single)
    <option value='{{$category_single->main_cat_id}}'>{{$category_single->main_cat_name}}</option>
  @endforeach
</select>