Laravel variant selection - default issue

Here is my Select Box, here the whole company will be loaded,

But I want to show a specific company as the default that I have in my 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 have tried is

 {{ Form::select('CompanyID', $comp, '', array('id' => 'seCompanyID'), array(id=>$sessioncompany)); }}

      

But I ended up with an error

What mistake am I making and how can I fix it?

Note. I want this in a laravel method.

+3


source to share


4 answers


$selectedId = ... // get the id from the session
{{ Form::select('CompanyID', $comp, array($selectedId), array('id' => 'seCompanyID')) }}

      



+6


source


The method Form::select()

has the following parameters:

  • $name

    - name

    HTML attribute
  • (array) $list

    - list of options, key-value pairs for actual value => displayed value
  • $selected

    - the value of the selected item
  • (array) $options

    - any additional HTML attributes, like other Form / HTML helper methods

So the third parameter $selected

is the one you want to pass to your session value. 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 the Laravel Form helpers is that you get the "old" login for free. For example, if you set the default here and the user changes it, the form will submit and there will be a validation error. When the form is redrawn (assuming you redirected back with return Redirect::back()->withInput();

), it will be set to the user-selected value, not an explicit default.

(Thanks to @JarekTkaczyk for putting me on the old input thing.)

+4


source


You are passing in the wrong parameters. max should be 4. Try this:

{{ Form::select('CompanyID', array('default' => $sessioncompany)+$comp, 'default') }}

      

+1


source


Just be careful, if you are on a page with a form with a select box, make sure that when you refresh each page while testing, you refresh the full page without using the cache - Ctrl + Shift + R

otherwise the last selected value may remain selected.

0


source







All Articles