我正在尝试将默认值绑定到选择标签。(在"编辑视图"中)。
我知道这应该很容易,但我认为我错过了一些东西。
我有:
用户.php(我的用户模型)
...
public function groups()
{
return $this->belongsToMany('App'Group');
}
public function getGroupListAttribute()
{
return $this->groups->lists('id');
}
...
用户控制器.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];
}
项目已正确选择,
现在我知道我必须从集合中获取一个数组。深入挖掘..:)
找到了它
用户.php:
...
public function getGroupListAttribute()
{
return $this->groups->lists('id')->toArray();
}
...
能更容易吗?
很好的问候,
克里斯托夫
你不应该把null
放在selected defaults
(3rd)参数中。
{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}
{!! Form::select(
'group_list[]',
$groups,
$user->group_list,
['multiple' => true]
)
!!}