【问题标题】:Filter with dropdown Laravel使用下拉菜单过滤 Laravel
【发布时间】:2015-04-02 09:59:15
【问题描述】:

我有一个用于按类别过滤图像的下拉菜单。我的第一个问题是我希望在过滤器之后选择选定的选项,我该怎么做?

这是我第一次使用 Laravel,我想知道我的解决方案是否朝着正确的方向发展(现在我在两个函数中有相同的代码,我打算修复它),但我不能真正找出做到这一点的最佳方法。我可以有一个接受类别或 null 的函数吗?

     <div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" value="">Show all</button>
        <ul class="dropdown-menu" role="menu">
            @foreach ($categories as $category)
               <li value="{{ $category->id }}"><a href="{{$category->id}}">{{ $category->name }}</a></li>
            @endforeach
        </ul>
     </div>

路线

Route::get('/', array('uses' => 'MyController@index'));
Route::get('/{category?}', array('uses' => 'MyController@filter'));

控制器

public function index()
{
    $images = Image::all();

    $categories = ..\Models\Category::all();

    return View::make('index', array('images' => $images, 'categories' => $categories));
}

public function filter($category){

    $images = Image::where('category_id', '=', $category);

    $categories = ..\Models\Category::all();

    return View::make('index', array('images' => $images, 'categories' => $categories));

}

【问题讨论】:

    标签: php twitter-bootstrap laravel


    【解决方案1】:

    在您看来,添加一个条件来检查循环中的当前类别是否是选定的类别。

    @foreach ($categories as $category)
        @if($category->id == Input::get('category')
               // echo category as selected
        @else
               // echo category
        @endif
    @endforeach
    

    您可能需要使用 html &lt;select&gt;

    您可以使用相同的方法来组合这两个功能。

    if(Input::has('category'))
         $images = Image::where('category_id', '=', $category);
    else
      $images = Image::all();
    

    这应该可以工作,因为您正在使用可选的路由参数。

    更新:

    如下使用select:

    @foreach ($categories as $category)
        <select onchange="filter(this.value)">
             @if($category->id == Input::get('category')
                 <option selected="selected" value="{{ $category->id }}">{{ $category->name }}</option>
             @else
                  <option value="{{ $category->id }}">{{ $category->name }}</option>
             @endif
       </select>
    @endforeach
    

    使用onchange属性将调用一个javascript函数,然后你可以使用重定向。

    <script>
        function filter(id)
        {
            window.location.href = {{ URL::action('Controller@filter') }} + '/' + id;
    </script>
    

    filter 是控制器中的函数。

    【讨论】:

    • 感谢您的回答,但我无法让它工作。我试过
    猜你喜欢
    • 2018-09-06
    • 2012-02-22
    • 2023-03-11
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多