Reputation: 4173
I have this checkbox code:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ $gallery->allowfullscreen == 1 ? 'checked' : '' }}>
</div>
This checks the checkbox based on the value taken from the database. Now, i would like to implement also the old data, in case of a failed submission.
For textboxes i do it like this:
<input id="galname"
type="text"
class="form-control @error('galname') is-invalid @enderror"
name="galname"
value="{{ old('galname') ?? $gallery->galname }}"
required autocomplete="galname" autofocus>
But it does not work this way for checkboxes since they need checked
to be printed. The samples I found around here on SO only adress one of the two situations, but didnt find any that address both things for checkboxes.
How can this be done?
Upvotes: 1
Views: 2155
Reputation: 536
This is ok even if you use all inputs in one blade template to use with create and update actions.
Will only work for POST
request, obviously.
@if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked @endif
<div class="form-group">
<input class="form-check-input" type="checkbox" id="publish" name="published" value="1" @if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked @endif>
<label class="form-check-label" for="publish">{{ __('Publié') }}</label>
@include('bo.modules.input-error', ['inputName'=>'published'])
</div>
Using this on request
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'published' => $this->published ? true : false
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'published' => 'required|boolean',
];
}
Upvotes: 0
Reputation: 571
The second parameter you give the the old()
function is used when the first value is null. So when you do old('name', "test")
and no old value for 'name' is found, 'test' is used. So in your case, you could use:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ old('allowfullscreen', $gallery->allowfullscreen) == 1 ? 'checked' : '' }}>
</div>
Upvotes: 2