在 Form::select 上重新填充 Laravel Input::old()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26025811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Repopulate Laravel Input::old() on Form::select
提问by PhilMarc
I can't manage to repopulate a Select field input after a query, using Laravel 4:
我无法使用 Laravel 4 在查询后重新填充 Select 字段输入:
// Route
Route::get('blog', 'BlogController@getPosts');
// BlogController
public function getPosts()
{
$posts = Post::where('category_id', Input::get('category'))->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, Input::old('category')) }}
{{ Form::close() }}
I managed to make it work this way, but it's not the best practice
我设法让它以这种方式工作,但这不是最佳实践
<select name="category" id="category">
<option value="1" {{ (Input::get('category') == 1) ? 'selected="selected"' : null }}>Category 1</option>
<option value="2" {{ (Input::get('category') == 2) ? 'selected="selected"' : null }}>Category 2</option>
<option value="3" {{ (Input::get('category') == 3) ? 'selected="selected"' : null }}>Category 3</option>
</select>
I think the Input::old('category')
doesn't work because it is a GET request, am I right? Is there any workarounds?
我认为Input::old('category')
它不起作用,因为它是一个 GET 请求,对吗?有什么解决方法吗?
Update : I finally made it work using Input::get()
instead of Input::old()
:
更新:我终于使它工作使用Input::get()
而不是Input::old()
:
{{ Form::select('category', $categories, Input::get('category')) }}
回答by aFreshMelon
It seems you're not even retrieving the old input, you will need to pass it to the view. You can do that in one of two ways, the easiest and best to understand is to just specify that you want to pass input.
似乎您甚至没有检索旧输入,您需要将其传递给视图。您可以通过以下两种方式之一来做到这一点,最容易和最好理解的就是指定您要传递输入。
return View::make('blog', compact('categories', 'posts'))->withInput();
Also, you don't need the markup in your HTML. Laravel will do this for you if you just give it the value of the old Input. It works very well.
此外,您不需要 HTML 中的标记。如果你只给它旧的 Input 的值,Laravel 会为你做这件事。它运作良好。
回答by RobbieP
Perhaps this will work
也许这会奏效
public function getPosts()
{
$category_id = Input::get('category');
$posts = Post::where('category_id', $category_id)->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts', 'category_id'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, $category_id) }}
{{ Form::close() }}