多个选择编辑表单选择的值

时间:2013-07-21 08:47:10

标签: many-to-many laravel laravel-4

在Laravel 4中遇到问题,在“联系人”模型编辑表单中,我可以获得所有字段的当前值,除了来自多个选择的那些,这是与另一个模型“公司”建立关系。这是一个多对多的关系。我正在获取公司列表,但即使存在关系,也不会选择任何公司。

这是我的编辑表格:

{{ Form::model($contact, array('route' => array('crm.contacts.update', $contact->id), 'id' => 'edit-contact')) }}
        <div class="control-group">
            {{ Form::label('first_name', 'First Name', array( 'class' => 'control-label' )) }}
            {{ Form::text('first_name') }}
        </div>
        <div class="control-group">
            {{ Form::label('last_name', 'Last Name', array( 'class' => 'control-label' )) }}
            {{ Form::text('last_name') }}
        </div>
        <div class="control-group">
            {{ Form::label('email', 'Company Email', array( 'class' => 'control-label' )) }}
            {{ Form::text('email') }}
        </div>
        <div class="control-group">
            {{ Form::label('company_ids', 'Company', array( 'class' => 'control-label' )) }}
            {{ Form::select('company_ids[]', $companies, array('',''), array('multiple'), Input::old('company_ids[]')) }}
        </div>
{{ Form::close() }}

我的控制器:

public function edit($id)
{
    $contact = Contact::find($id);
    $company_options = Company::lists('name', 'id');
    return View::make('crm.contacts.edit')
        ->with('contact', $contact)
        ->with('companies', $company_options);;
}

有关如何使多个选择字段预先填充现有值的任何想法?

由于

2 个答案:

答案 0 :(得分:12)

Laravel默认支持多​​选字段你需要使用Form :: macro

以下@Itrulia的例子是正确的,您可以这样做:

$users = array(
    1 => 'joe',
    2 => 'bob',
    3 => 'john',
    4 => 'doe'
);
echo Form::select('members[]', $users, array(1,2), array('multiple' => true));

答案 1 :(得分:10)

Laravel默认支持多选。

{{ Form::select('members[]', $users, null, array('multiple' => true)); }}