laravel 多选编辑表单选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17770581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:10:08  来源:igfitidea点击:

Multiple select edit form selected values

many-to-manylaravellaravel-4

提问by maunoxyd

Struggling with an issue in Laravel 4, in a "contact" model edit form, I can get all fields current values except those from the multiple select which is to establish a relation with another model "company". It's a many-to-many relationship. I'm getting the list of companies, but none are selected even if a relation exists.

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

Here's my edit form:

这是我的编辑表格:

{{ 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() }}

My controller:

我的控制器:

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);;
}

Any ideas on how to have the multiple select field pre-filled with existing values?

关于如何使用现有值预填充多选字段的任何想法?

Thanks

谢谢

回答by Ryun

Laravel does notsupport multi-select fields by default you need to use a Form::macro

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

The example below by @Itrulia was correct, you can simply do:

@Itrulia 下面的例子是正确的,你可以简单地做:

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

回答by Itrulia

Laravel does support multiselect by default.

Laravel 默认支持多选。

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