2015-06-21 100 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

雖然這可行,但如果你這樣做,你不再使用模型綁定。 –