【问题标题】:Multiple select edit form selected values多选编辑表单选定值
【发布时间】:2013-07-21 08:47:10
【问题描述】:

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

关于如何让多选字段预填充现有值有什么想法吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 哪里是插入这个的最佳位置?开始.php?谢谢
    • 当然,我使用了一个文件 FormMacros.php 并将它包含在 app/start/global.php 中
    • array(1,2) 应该是选中的项目,不是吗?我试过了,但它不起作用。请,需要更多解释。谢谢。 @Ryun
    • 能否在控制器中也包含store()方法和RDBM表的结构?对此非常重要。
    【解决方案2】:

    Laravel 默认支持多选。

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

    【讨论】:

    • 可以设置html属性,但不会将selected fields变量作为数组处理。selected参数只接受字符串..
    • 不,那是错误的。其中 null 只是设置了一个值数组,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 2019-01-12
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多