我的 CRUD 表单在 Laravel 10 中工作,但选择下拉菜单更新功能除外。在 CREATE 功能中,我可以成功地从表单(不是表格)的选项列表中选择所需的值。它完美地存储了这些数据,我可以在我的数据库表中看到它。当我从编辑/更新页面打开数据时,未选择所选数据值,并且我希望更改该值,但它不会存储它,并且初始值保留在数据库中。 这是我的更新表格:
<form method="get" action="{{route('receipts.update', ['receipts' => $receipts])}}">
@csrf
@method('put')
<div>
<label for="payee">Payee:</label>
<input type="text" name="payee" placeholder="Payee Name" value="{{$receipts->payee}}">
</div>
<div>
<label for="amount">Amount:</label>
<input type="text" name="amount" placeholder="Amount" value="{{$receipts->amount}}">
</div>
<div>
<label for="date">Date:</label>
<input type="date" name="date" value="{{$receipts->date}}">
</div>
<div>
<label for="description">Description:</label>
<input type="text" name="description" placeholder="Description" value="{{$receipts->description}}">
</div>
<div>
<label for="cost">Cost Center:</label>
<select type="text" name="cost">
<option value="{{$receipts->cost}}">Personal</option>
<option value="{{$receipts->cost}}">CC1</option>
<option value="{{$receipts->cost}}">CC2</option>
<option value="{{$receipts->cost}}">CC3</option>
<option value="{{$receipts->cost}}">Other</option>
</select>
</div>
</div>
<div>
<input type="submit" value="Add Receipt">
</div>
</form>
这是我在控制器中的更新方法:
public function update(Receipts $receipts, Request $request){
$data = $request->validate([
'payee' => 'required',
'amount' => 'required|decimal:0,2',
'date' => 'required',
'description' => 'nullable',
'cost' => 'required'
]);
$receipts->update($data);
return redirect(route('receipts.index'))->with('success', 'Receipt Updated Successfully');
}
我相信我正在从数据库中读取所选值,但该值选项未在表单中显示为所选值,最重要的是,新值未被存储/更新。 我试过这个:
<option {{ old('cost') == $data ? "selected" : "" }} value="{{ $cost }}">
但是这会破坏并且不推荐用于 Laravel 10 及更高版本。我需要 if / else 语句才能完成这项工作吗?我搜索了其他示例,但它们似乎从单独的表中获取值选项,而不是内联的。任何建议表示赞赏。
抱歉,我浪费了社区的时间,但我找到了一个解决方案,也许它会帮助其他人。这比预期的要容易得多。由于我有一个工作控制器,我需要使用 Laravel 提供的附加属性 @selected 指令:
<select type="text" name="cost">
<option value="Personal" {{ $receipts->cost == 'Personal' ? 'selected' : '' }}>Personal</option>
<option value="CC1" {{ $receipts->cost == 'CC1' ? 'selected' : '' }}>CC1</option>
<option value="CC2" {{ $receipts->cost == 'CC2' ? 'selected' : '' }}>CC2</option>
<option value="CC3" {{ $receipts->cost == 'CC3' ? 'selected' : '' }}>CC3</option>
<option value="Other" {{ $receipts->cost == 'Other' ? 'selected' : '' }}>Other</option>
</select>
谢谢你