我有一个Laravel应用程序,它使用表单来创建项目。表单使用this section下Laravel文档中定义的验证。
我有一个StoreItem请求文件:
public function rules() {
return [
'item_name'=>'required',
'category_id'=> 'required',
'collection_id'=> 'required',
'brewery_id'=> 'required',
];
}
,在控制器中,我有以下内容:
public function store(storeItem $request)
{
$validated = $request->validated();
$item = new Item([
'user_id' => Auth::id(),
'item_name' => $request->item_name,
'category_id' => $request->category_id,
'collection_id' => $request->collection_id,
'brewery_id' => $request->brewery_id,
]);
$item->save();
当验证发现错误时,将再次显示创建表单,但我看不到旧的输入数据。
对于输入文本字段,我已经执行了以下操作:
<input type="text" class="form-control" name="item_name" value="{{ old('item_name') }}" />
,它显示了旧的输入数据,但对下拉框(如category_id,collection_id和brewery_id)要做什么。我希望他们将旧值作为“选定”值。
当前为我拥有的形式(用于下拉框):
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
@foreach($breweries as $brewery)
<option value="{{ $brewery->id }}">{{ $brewery->brewery_name }}</option>
@endforeach
</select>
</div>
This的来源似乎表明甚至不需要使用old()方法,但是如果我不使用
答案 0 :(得分:2)
您需要手动将selected
属性添加到先前选择的值。例如:
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
@foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ old("brewery_id") == $brewery->id ? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
@endforeach
</select>
</div>
答案 1 :(得分:1)
也尝试一下。我已将括号添加到(old('brewery_id')==$brewery->id)
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
@foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ (old('brewery_id') == $brewery->id)? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
@endforeach
</select>
</div>