【问题标题】:Laravel PHP: Keep the chosen dropdown option stay selected on ViewLaravel PHP:保持选中的下拉选项在视图上保持选中状态
【发布时间】:2014-11-19 04:58:17
【问题描述】:

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

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

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

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

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

控制器:

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

我尝试了几种方法将选择的“类别”变量传递回下拉列表,以便在用户做出选择后它会保留在所选选项上,但它们都没有为我工作。任何帮助是极大的赞赏!

【问题讨论】:

    标签: php laravel-4


    【解决方案1】:

    你可以试试这个:

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

    【讨论】:

    • 这种方法的问题是,在用户做出选择并提交后,下拉框将始终保持在“Category1”上的选中状态。
    • 你应该传递$category数组否则默认category1会被选中。
    • 问题是我不确定如何将 $category 数组从控制器传递到表单。
    • 您正在传递$data,只需在使用$this-&gt;layout-&gt;content =... 传递之前添加$data['category']=Input::get('category')
    • 我添加了 '$data['category'] = Input::get('category');'在我将代码传递给 '$this->layout->content=...' 代码行之前添加到我的代码,现在它可以完美运行,非常感谢@The Alpha!
    【解决方案2】:

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

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

    【讨论】:

    • 我尝试了这种方法,但在用户提交选择后,它仍然恢复到下拉框中的第一个选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 2011-03-07
    • 1970-01-01
    • 2017-12-25
    • 2012-08-25
    相关资源
    最近更新 更多