【发布时间】:2017-05-31 18:29:35
【问题描述】:
我有一个搜索表单,但提交时它不显示之前选择的选项。
这是我的表格:
<form role="form" class="advanced-search-form" method="post" action="{{ url('/searchresults') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-4 form-group">
<label for="exampleSelect1">Select city: </label>
<select class="form-control" id="exampleSelect1" name="selectcity">
@if (count($cities) > 0)
@foreach ($cities as $city)
<option value="{{$city->id}}" @if( old('selectcity') == $city->id) selected="selected" @endif>{{$city->name}}</option>
@endforeach
@endif
</select>
</div>
<div class="row">
<div class="form-group col-md-4 col-md-offset-8">
<button class="btn btn-light-blue-2 pull-right" type="submit">Search</button>
</div>
</div>
</form>
这是我的路线: Route::post('/searchresults', 'SearchController@index');
我的控制器中的操作
public function index()
{
$cities = DB::table('cities')
->select('cities.name', 'cities.id')
->orderBy('name', 'ASC')
->get();
return view('pages.searchresults', compact('cities'));
}
在我没有显示结果的那一刻,我首先需要修复为什么表单在提交后为空,并且不返回旧值并设置选定的选项。
【问题讨论】:
-
在发布方法上重定向而不是返回视图。
-
首先:在处理表单并想要填充它们时,您真的应该查看laravelcollective.com/docs/5.0/html。其次 - 您是否有理由不使用 City 模型而不是进行原始查询?第三 - 要重定向回表单并保留数据,您可以使用 redirect()->back()->withData() 并包括 ->with(compact('cities'))
-
old()仅在您将旧输入数据刷新到会话时才有效,如文档所述。如果您想记住这些数据,则必须手动将其刷新或将所选值发送回您的页面。 -
@larsemil 感谢您的提示。 2. 我还没有创建模型,我的第一个方法是使用数据库查询。问题是我不想重定向回来,而是重定向到不同的视图
-
@Jerodev 谢谢你的建议,问题解决了
标签: laravel select form-submit blade