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 option
s 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.