2017-10-15 60 views
1

我試圖讓一個表格中的multiselect工作,我使用laravel,我傳遞給我的視圖變量名爲相關,一個ID數組,引用相關選擇的模式模型,這裏就是我做的對抗代碼:Laravel刀片形狀Multiselect選擇使用陣列不工作

@foreach($categories as $category) 

       @foreach($correlated as $c) 
       @if($c === $brand_id) 
       @php($selected = "selected") 
       @endif 
       @endforeach 
       <option class="text-center" value="{{ $category->id }}" selected="{{ $selected }}">{{ ucfirst($category->name) }}</option> 
       @endforeach 

我檢查都brand_id和$ C值,他們是正確的。有任何想法嗎?


編輯:修正,似乎是最正確的,這樣,仍然沒有工作...

@php $selected = "" @endphp 
      <select multiple name="categoriesField[]" class="form-control" size="{{ count($categories) }}"> 
       @foreach($categories as $category) 
       @php $selected = '' @endphp 
       @if(in_array($category->id, $correlated)) 
       @php $selected = 'selected' @endphp 
       @endif    
       <option class="text-center" value="{{ $category->id }}" @php echo $selected @endphp>{{ ucfirst($category->name) }}</option> 
       @endforeach 
      </select> 

編輯2:與上面的代碼解決了,我的瀏覽器表現得莫名其妙的錯誤,沒不要顯示選定的選項,我想查看唯一的答案。

回答

1

您可以在一個變量

@php $brandIds = collect($correlated)->toArray() @endphp 

試試這個

<select>標籤存儲件之前的品牌IDS裏面你<select>標記檢查,如果你$brand_id變量的值是使用PHP in_arrya()$brandIds陣列內功能,然後選擇該選項。

@foreach($categories as $category) 
    <option class="text-center" value="{{ $category->id }}" @if(in_array($brand_id, $brandIds)) selected @endif>{{ ucfirst($category->name) }}</option> 
@endforeach 

希望這會爲你工作:)

+0

我需要面對$相關(一組ID)和$類別 - > id,這將不是一個數組(和containes的ID來檢查激活所以我不能使用in_array – K3nzie

+0

'in_array()'函數將第一個參數作爲一個字符串和第二個數組,因此您可以使用它,第一個參數作爲'$ category-> id'和秒參數作爲'$ correlated'我存儲在'$ brandIds'中,所以你可以使用'$ branchIds'作爲in_array()函數的第二參數 – Vikash

+1

是的,現在我知道了,事實上它確實工作 – K3nzie