问题
Here is my Select Box, Here All Company will be loaded,
But i want to display the Particular company as default selected which i have it in session.
Here is my Code
$sessioncompany = 'ABCcompany'
$comp[''] = 'Company';
@foreach($company_list as $row)
<?php
$comp[$row->CompanyID] = $row->CompanyName;
?>
@endforeach
{{ Form::select('CompanyID', $comp, '', array('id' => 'seCompanyID')); }}
What i tried is
{{ Form::select('CompanyID', $comp, '', array('id' => 'seCompanyID'), array(id=>$sessioncompany)); }}
But i ended with failure
What is the mistake i am doing and How can i fix that ?
Note : I want it in the native laravel method
回答1:
$selectedId = ... // get the id from the session
{{ Form::select('CompanyID', $comp, array($selectedId), array('id' => 'seCompanyID')) }}
回答2:
The Form::select()
method has the following parameters:
$name
- thename
HTML attribute(array) $list
- the list of options, key-value pairs for actual value => displayed value$selected
- the selected item's value(array) $options
- any extra HTML attributes, as per other Form/HTML helper methods
So, the third parameter $selected
is the one you want to pass your session value to. Copying your example and replacing:
{{ Form::select('CompanyID', $comp, Session::get('my_session_var'), array('id' => 'seCompanyID')); }}
Where 'my_session_var'
is the name of the session variable you store the value of the item that should be selected by default.
The great thing about using Laravel's Form helpers is that you get the 'old' input for free. For example, if you set a default here and the user changes it, submits the form and there's a validation error. When the form is redisplayed (assuming you redirected back with return Redirect::back()->withInput();
) the value the user selected, rather than your explicit default will be set.
(Thanks to @JarekTkaczyk for putting me right on the old input thing.)
回答3:
You are passing wrong parameters. max parameters should be 4. Try this:
{{ Form::select('CompanyID', array('default' => $sessioncompany)+$comp, 'default') }}
回答4:
Just beware, if you're on a page with the form with the select box, make sure that with each page refresh while testing you do a full page refresh without using cache - Ctrl + Shift + R
, otherwise the last selected value may remain selected.
来源:https://stackoverflow.com/questions/26990844/laravel-option-select-default-issue