Jeff P.
Jeff P.

Reputation: 3004

Laravel PHP: Keep the chosen dropdown option stay selected on View

I have a homepage that contains a dropdown menu that allows the user to select a category and will display results depending on which option is chosen from the dropdown menu.

It is currently working fine in updating and displaying the correct results but now I've run into a minor issue where I want the dropdown to stay selected on the chosen category. Normally I would put a simple line of code within my view such as

{{ Form::label('category', 'Category:') }}
{{ Form::select('category', array('option1' => 'Option1', 'option2' => 'Option2'), $video->category) }}

where $video is the model used in the controller.

However this situation is a little bit different because I need to pass the 'category' variable from within my controller so that the dropdown menu will stay on the selected category after the user makes their choice.

Controller:

public function index()
{
    $vdo = Video::query();
    $pic = Picture::query();
    if($category = Input::get('category')){
        $vdo->where('category', $category);
        $pic->where('category', $category);
    }

    $allvids = $vdo->paginate(10);
    $allpics = $pic->paginate(10);
    $data = compact('allvids','allpics');
    $this->layout->content = \View::make('home.pics_vids_overview',$data)->with('category', Input::get('category'));
}

View:

{{Form::open(array('route' => 'overview_select', 'files' => true)) }}    

<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', array('Category1' => 'Category1', 'Category2' => 'Category2', 'Category3' => 'Category3', 'Category4' => 'Category4'), array('class' => 'form-control')) }}

I've tried several approaches in passing the chosen 'category' variable back to the dropdown so that it will stay on the chosen option after the user makes their choice but none of them have worked for me yet. Any help is greatly appreciated!

Upvotes: 0

Views: 1198

Answers (2)

Peter Gluck
Peter Gluck

Reputation: 8236

Use Form::model instead of Form::open to bind the model to the form and it will automatically pick up any values in the model:

{{ Form::model(array('route' => 'overview_select', 'files' => true)) }}    

Upvotes: 0

The Alpha
The Alpha

Reputation: 146201

You may try this:

{{ 
    Form::select(
       'category',
       array('Category1' => 'Category1', 'Category2' => 'Category2'),
       (isset($category) ? $category : 'Category1'),
       array('class' => 'form-control')
    )
}}

Upvotes: 1

Related Questions