Laravel PHP:在“视图”上保持选中所选的下拉选项


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

我有一个主页,其中包含一个下拉菜单,允许用户选择一个类别,并根据从下拉菜单中选择的选项显示结果。

它目前在更新和显示正确结果方面工作正常,但现在我遇到了一个小问题,我希望下拉列表在所选类别上保持选中状态。 通常我会在我的视图中放置一行简单的代码,例如

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

其中$video是控制器中使用的模型。

但是,这种情况略有不同,因为我需要从控制器中传递"category"变量,以便在用户做出选择后下拉菜单将保留在所选类别上。

控制器:

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'));
}

视图:

{{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')) }}

我已经尝试了几种将所选"类别"变量传递回下拉列表的方法,以便在用户做出选择后它将保留在所选选项上,但这些方法都不适合我。 任何帮助将不胜感激!

你可以试试这个:

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

使用Form::model而不是Form::open将模型绑定到表单,它将自动获取模型中的任何值:

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