【发布时间】:2015-09-07 07:23:17
【问题描述】:
我正在尝试将默认值绑定到选择标记。 (在“编辑视图”中)。
我知道这应该很容易,但我认为我遗漏了一些东西。
我有:
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];
}
项目被正确选择,
现在我知道我必须从集合中获取一个数组.. 深入挖掘.. :)
找到了
用户.php:
...
public function getGroupListAttribute()
{
return $this->groups->lists('id')->toArray();
}
...
会更简单吗?
问候,
克里斯托夫
【问题讨论】:
-
仅供参考,您可以这样做而无需在
User.php中声明getGroupListAttribute()方法 -
我遇到了类似的问题,而不是在 edit.blade 视图的 Form::select 的第三个参数中使用 null,把你的 $user 属性。类似于
$user->groups。我已经使用单个元素下拉菜单完成了此操作,但您必须使用多个元素进行测试。
标签: php html laravel binding blade