简体   繁体   English

Laravel 多选下拉值不显示在编辑表单中

[英]Laravel Multi-select dropdown value not display in edit form

I have table user and branch like this我有这样的表用户和分支

id name  branch_code
1  ABC   ["011","012","013","014"]
2  DEF   ["014"]

table branch表分支

id branch_code branch_name
1   011        XXX
2   012        YYY
3   013        ZZZ
4   014        WWW

when create a new user, there is multi-select dropdown for BRANCH, so one user can select many branches.创建新用户时,BRANCH 有多选下拉菜单,因此一个用户可以选择多个分支。

i can save the multi-select dropdown it into table user in column branch_code.我可以将多选下拉列表保存到 branch_code 列中的表用户中。 But i have problem to show the selected value in edit form但是我在编辑表单中显示所选值时遇到问题

here is the multi-select dropdown for edit form这是编辑表单的多选下拉菜单

<select class="form-control" name="branch[]" id="users" multiple>
        @foreach ($branch as $branch)
             <option @if ($branch->branch_code==$user->branch_code)
                      selected
                    @endif value="{{$branch->branch_code}}">
                    {{$branch->branch_name}}
             </option>
         @endforeach
   </select>

the edit controller编辑控制器

 public function edit($id)
{
  
    $branch = Branch::where('status','1')->get();
    $user = User::where('id',$id)->first();
    return view('admin.edit', compact('user','branch'));
}

in edit form, i want to show all branches with selected branches and also unselected branches in the dropdown.在编辑表单中,我想在下拉列表中显示所有带有选定分支和未选定分支的分支。 and for selected branches, it will highlighted with "selected" remark or something like that.对于选定的分支,它将用“选定”注释或类似的东西突出显示。 But now it's only show all branches and no remark for selected branches但现在它只显示所有分支,对选定的分支没有备注

$user->branch_code is array or json string of an array. $user->branch_code是数组或数组的 json 字符串。

If it's json string then $user->branch_code = json_decode($user->branch_code) first.如果是 json 字符串,则$user->branch_code = json_decode($user->branch_code)首先。

When you have array - you can do something like:当您拥有数组时 - 您可以执行以下操作:

<option
    @if (in_array($branch->branch_code, $user->branch_code)) selected @endif
    value="{{$branch->branch_code}}"
>
    {{$branch->branch_name}}
</option>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM