2015-06-21 98 views
11

我试图将默认值绑定到选择标记。 (在“编辑视图”中)。Laravel表单模型绑定多选择默认值

我知道这应该很容易,但我想我错过了一些东西。

我:

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' => ['[email protected]', $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(); 
} 
... 

可能是更容易?

尼斯的问候,

克里斯托夫

+0

强制仅供参考,你可以做,而不必申报'User.php' – xhulio

+0

我遇到类似的问题'getGroupListAttribute()'方法,而不是使用*空*中的第三个参数* Form :: select *在你的edit.blade视图中,放置你的$ user属性。会像'$ user-> groups'一样。我已经完成了单元素下拉菜单,但你必须用多个元素来测试。 – alariva

回答

2

你不应该把nullselected defaults(3)的说法。

{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!} 

{!! Form::select(
     'group_list[]', 
     $groups, 
     $user->group_list, 
     ['multiple' => true] 
    ) 
!!} 
+0

虽然这可行,但如果你这样做,你不再使用模型绑定。 –