在我的 laravel 刀片文件中,我有一个多选框,值来自数据库/控制器。以下是值:
[{"id":1,"name":"United States"},{"id":2,"name":"United Kingdom"},{"id":3,"name":"China"}]
我想显示多选框中的值以及用户已经选择的值(来自另一个变量中的控制器(,见下文;
[{"id":2,"name":"英国"}]
下面是多选框的代码:
<select multiple="multiple" name="warehouseId[]" id="warehouse" class="form-control" style="width:100%;" required>
@if($warehouseData)
@foreach ($warehouseData as $key => $warehouse)
<option value="{{$warehouse->id}}" @if($adminUserWarehouseSelectedData[$key]->name == $warehouse->name) Selected @endif>{{$warehouse->name}}</option>
@endforeach
@endif
</select>
但它最终出现了一个错误——
未定义的偏移量:1
试试这段代码
<select multiple="multiple" name="warehouseId[]" id="warehouse" class="form-control" style="width:100%;" required>
@if($warehouseData)
@foreach ($warehouseData as $warehouse)
<option value="{{$warehouse->id}}" @foreach($adminUserWarehouseSelectedData as $data) @if($data->name == $warehouse->name) Selected @endif @endforeach>{{$warehouse->name}}</option>
@endforeach
@endif
</select>
错误之所以存在$adminUserWarehouseSelectedData
是因为此变量包含多个数据,我们试图将其视为单个数据。 所以你必须为此做一个循环。