[英]Laravel Form-Model Binding multi select default values
我正在嘗試將默認值綁定到選擇標記。 (在“編輯視圖”中)。
我知道這應該很容易,但我想我錯過了一些東西。
我有:
User.php (我的用戶模型)
...
public function groups()
{
return $this->belongsToMany('App\Group');
}
public function getGroupListAttribute()
{
return $this->groups->lists('id');
}
...
UserController.php (我的控制器)
...
public function edit(User $user)
{
$groups = Group::lists('name', 'id');
return view('users.admin.edit', compact('user', 'groups'));
}
...
edit.blade.php (視圖)
...
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['UserController@update', $user->id]]) !!}
...
...
// the form should be binded by the attribute 'group_list' created
// at the second block of 'User.php'
// performing a $user->group_list gets me the correct values
{!! Form::select('group_list[]', $groups, null, [
'class' => 'form-control',
'id' => 'grouplist',
'multiple' => true
]) !!}
...
我在我的刀片上做了一個虛擬測試,並得到了正確的結果:
@foreach ($user->group_list as $item)
{{ $item }}
@endforeach
這列出了默認情況下應該選擇的值。
我還嘗試將$user->group_list
作為Form::select
第三個參數,但這並沒有工作以太......
我不知道我做錯了什么..對這個有任何暗示嗎?
編輯
當我做:
public function getGroupListAttribute()
{
//return $this->groups->lists('id');
return [1,5];
}
該項目已正確選擇,
現在我知道我必須從集合中獲取數組..深入挖掘.. :)
找到了
user.php的:
...
public function getGroupListAttribute()
{
return $this->groups->lists('id')->toArray();
}
...
它會更容易嗎?
很好的問候,
克里斯托夫
您不應該在selected defaults
(3rd)參數中放置null
。
{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}
{!! Form::select(
'group_list[]',
$groups,
$user->group_list,
['multiple' => true]
)
!!}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.