在 laravel 5 中验证后重新填充表单中的复选框字段
Repopulate checkbox fields in the form after validation in laravel 5
我试图在 Laravel 中验证后重新填充复选框字段。实际上,复选框字段名称为数组。示例:
<form name="" action="" method="post">
<div class="row>
<input type="checkbox" name="models[]" value="1">Model 1
<input type="checkbox" name="models[]" value="2">Model 2
<input type="checkbox" name="models[]" value="3">Model 3
<input type="checkbox" name="models[]" value="4">Model 4
<input type="checkbox" name="models[]" value="5">Model 5
</div>
<div class="row>
<input type="checkbox" name="model_name" value="" placeholder="Model Name">
</div>
<div class="row>
<input type="submit" name="submit" value="submit">
</div>
</form>
我的表单将如下所示。所以提交表单后会出现验证错误,我需要在验证错误后重新填充复选框值。我已经尝试使用 {{ old('field_name') }} 来选中复选框。但它不起作用。有人有解决这个问题的方法吗?
你很接近!如果检测到 model_name
的旧值,您只需要 'reactivate' 通过将单词 'checked' 放在 <input>
元素中来 [=15=] 检查的方式。
<input type="checkbox" name="model_name" value="" placeholder="Model Name">
@if (old('model_name'))
checked
@endif
/>
我在Laravel 5.5
中尝试了类似下面的代码
<input type="checkbox" name="models[]" value="1" @if( is_array(old('models')) && in_array(1, old('models'))) checked @endif >Model 1
这对我有用 (Laravel 5.2)
@foreach ($models as $model)
<input type="checkbox" name="models[{{ $model->id }}]"
@if (is_array(old('models')) && in_array($model->id, array_keys(old('models'))))
checked
@endif
> {{ $model->name }}
@endforeach
我试图在 Laravel 中验证后重新填充复选框字段。实际上,复选框字段名称为数组。示例:
<form name="" action="" method="post">
<div class="row>
<input type="checkbox" name="models[]" value="1">Model 1
<input type="checkbox" name="models[]" value="2">Model 2
<input type="checkbox" name="models[]" value="3">Model 3
<input type="checkbox" name="models[]" value="4">Model 4
<input type="checkbox" name="models[]" value="5">Model 5
</div>
<div class="row>
<input type="checkbox" name="model_name" value="" placeholder="Model Name">
</div>
<div class="row>
<input type="submit" name="submit" value="submit">
</div>
</form>
我的表单将如下所示。所以提交表单后会出现验证错误,我需要在验证错误后重新填充复选框值。我已经尝试使用 {{ old('field_name') }} 来选中复选框。但它不起作用。有人有解决这个问题的方法吗?
你很接近!如果检测到 model_name
的旧值,您只需要 'reactivate' 通过将单词 'checked' 放在 <input>
元素中来 [=15=] 检查的方式。
<input type="checkbox" name="model_name" value="" placeholder="Model Name">
@if (old('model_name'))
checked
@endif
/>
我在Laravel 5.5
中尝试了类似下面的代码<input type="checkbox" name="models[]" value="1" @if( is_array(old('models')) && in_array(1, old('models'))) checked @endif >Model 1
这对我有用 (Laravel 5.2)
@foreach ($models as $model)
<input type="checkbox" name="models[{{ $model->id }}]"
@if (is_array(old('models')) && in_array($model->id, array_keys(old('models'))))
checked
@endif
> {{ $model->name }}
@endforeach