我有一个下拉菜单,用于按类别过滤图像。我的第一个问题是我希望在过滤器之后选择选定的选项,我该怎么做?
这是我第一次使用 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>
routes
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));
}
在您的视图中,添加一个条件来检查循环中的当前类别是否为所选类别。
@foreach ($categories as $category)
@if($category->id == Input::get('category')
// echo category as selected
@else
// echo category
@endif
@endforeach
您可能需要使用 html<select>
.
您可以使用相同的方法来组合这两个功能。
if(Input::has('category'))
$images = Image::where('category_id', '=', $category);
else
$images = Image::all();
这应该有效,因为您正在使用可选的路由参数。
Update:
使用选择如下:
@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>
where filter
是控制器中的功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)