在一个表格中,我有多个选择
<div class="form-group">
<label>Seasons</label>
<select class="form-control" name="year_code" required>
<option value="{{ Input::old ('year_code') }}"
selected>{{ Input::old ('year_code') }}</option>
<div class="divider"></div>
<option value="16">2016-2017</option>
<option value="17">2017-2018</option>
<option value="18">2018-2019</option>
<option value="20">2020-2021</option>
</select>
</div>
如果验证由于错误的值而失败(php 端验证)我的表格返回旧输入,假设选择了 2016-2017 赛季如果我的表单失败,则返回值将为 16,并且将显示。我可以做多个 if 语句,例如
@if('Input::get(year_code) == 16)
show 2016-2017
@elseif ('Input::get(year_code) == 17)
show 2017-2018
...
@endif
但我正在寻找更有效的方式来获取值的名称。
与其硬编码,不如将它们保存在多维数组中,以便您可以更轻松地进行操作。
$arr = [
["value" => 16, "text" => "2016-2017"],
["value" => 17, "text" => "2017-2018"],
["value" => 18, "text" => "2018-2019"]
...
];
使用 ViewComposer 将该数据传递到您的视图。
@foreach($arr as $entry)
@if((int) Input::old('year_code') === $entry['value'])
<option value="{{ $entry['value'] }}" selected>{{ $entry['text'] }}</option>
@else
<option value="{{ $entry['value'] }}">{{ $entry['text'] }}</option>
@endif
@endforeach
此外,似乎可以自动生成值。我个人会创建一个看起来像这样的日期迭代器。(伪)
public function getYears(int $diff): array {
$start = Date::today()->startOfYear();
$end = Date::today()->addYears($diff)->startOfYear();
$response = [];
$start->diffInYears($end, function ($year) use (&response) {
$response[] = sprintf("%s - %s", $year->format("Y"), $year->addYear()->format("Y"));
});
return $response;
}
<div class="form-group">
<label>Seasons</label>
<select class="form-control" name="year_code" required>
<option value="16" {{'Input::get(year_code)==16?'selected':''}}>2016-2017</option>
<option value="17" {{'Input::get(year_code)==17?'selected':''}}>2017-2018</option>
<option value="18" {{'Input::get(year_code)==18?'selected':''}}>2018-2019</option>
<option value="20" {{'Input::get(year_code)==20?'selected':''}}>2020-2021</option>
</select>
</div>