Mhluzi Bhaka
Mhluzi Bhaka

Reputation: 1392

Dropdown to either display a "Please select" option or display the "selected" option in Laravel 5

I have the following code to create a dropdown:

<div>
<label>Project List:</label>
{!!Form::select('projects_list[]', $projects_list, $project, ['id'=> 'projects_list','class'=>'form-control'])!!}
</div>

That works fine and it will display the selected project from $project on page load.

($projects_list is a list of all projects and $project is a specific selected project)

If I add in a bit of code to create a "Please select option";

<div>
<label>Project List:</label>
{!!Form::select('projects_list[]', array_merge(['0' => 'Please select'], $projects_list), $project, ['id'=> 'projects_list','class'=>'form-control'])!!}
</div>

That shows the option correctly if no project is passed through on page load but then does not display the project if it is passed through.

Is there perhaps another way to display the option for "Please select" and still to be able to show the selected project?

**** EDIT ****

What I am doing in the meantime is:

In my controller:

$projects_list = Project::lists('id','name');

$projects_list = array_flip(array_merge(['Please select if applicable'=>0], $projects_list));   

I have found that if I don't do that array flip / array merge the id's get converted to keys such as 0,1,2,3 instead of the database id's of 0, 10,15,23 whatever.

Perhaps this is the best option for now? Or is there a more elegant solution?

**** END EDIT ****

Upvotes: -1

Views: 1036

Answers (1)

Ben Swinburne
Ben Swinburne

Reputation: 26477

To add another option you can use the + operator to put two arrays together without affecting the keys

$projects_list = ['Please select if applicable'] + $projects_list;

Upvotes: 0

Related Questions