dongqian9567 2017-06-20 06:28
浏览 395

Laravel 5.4中的多个Form :: select中的默认值

I use Laravel 5.4 with Collective\Html package.

I try to build a form with multiple select element and set a default values for it.

My form.blade.php file

{!! Form::open(['url'=>'', 'method'=>'GET']) !!}

    {!! Form::select(
        "fruits[]",
        [1=>"apple", 2=>"peer", 3=>"banana"],
        [1, 3],
        ["multiple"=>true]
        );
    !!}

    ...

{!! Form::close() !!}

This code works fine and I see multi-line select element with selected first and third lines.

But if I send to this page GET data through url like /form?fruits[]=2&fruits[]=3 pre-selected valued are not available any more.

As far as I understand, the reason is in Collective\Html\FormBuilder class. Beginning from v5.2 following code was added to the getValueAttribute() method (lines 1163-1166 at v.5.4):

$request = $this->request($name);
if (!is_null($request)) {
    return $request;
}

This code returns and overrides default values from Form::select() and takes needed values from the request. It is nice, but looks like developers do not have a full control under select element after this update.

After some manipulations in the FormBuilder class, default values are sent to the getSelectedValue() method, which set 'selected' attribute for needed options in select element (lines 762-764)

if (is_array($selected)) {
    return in_array($value, $selected, true) ? 'selected' : null;
//--------------------------------------^-----------------
//-------------------------------problem origin-----------
}

Here in_array looks for option value ($value) in default values from url ($selected). As far values from url are strings and $value is integer FormBuilder does not find default options at all.

How to set default values without editing source class? Should I override HtmlServiceProvider, HtmlBuilder and FormBuilder classes just to remove true parameter?

Maybe there is some more native way to set default values?

Thanks in advance for your answers.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP