Reputation: 14520
There are many many questions here on SO about how to properly persist checkbox fields in Laravel after form submission ( example, example, example ), this question is not about that.
Please note I am also well aware of Laravel's old()
method, and that it accepts a default value. My question is about a particular case where old()
does not seem to work for a checkbox.
I'm working on an edit form, updating data already in the DB. The form will initially be populated with the values from the DB.
The standard approach to re-populating form inputs after failed validation is to use old()
. For most input types, something like the following works:
<input type='text' name='unicorns' value='{{ old('unicorns', $model->unicorns) }}'>
On initial page load (before the form is submitted) this works fine. As nothing has been submitted yet, old('unicorns')
is null
, so the default of $model->unicorns
will be used, and the text field's value reflects the current DB state.
After submitting a new value, which fails validation, old('unicorns')
will be the new value, even if the new value was an empty string, and again the text field's value reflects the submitted state, as we want.
However this breaks down for checkboxes, when the unchecked checkbox does not appear in the request at all. Consider:
<input type='checkbox' name='unicorns' value='1' @if old('unicorns', $model->unicorns) checked @endif>
On initial page load this works fine, just like for text fields. But after failed validation, for the 2 cases where the checkbox is changed from its initial state:
Case 1: DB state 0
(unchecked), submitted state checked. old('unicorns')
will be 1
, so the test evaluates true
, the checkbox is checked - OK!
Case 2: DB state 1
(checked), submitted state unchecked. Since old('unicorns')
is null, old()
falls back to the default value $model->unicorns
(1
), so the test evaluates true
, and the checkbox is checked - but we just unchecked it! FAIL!
(There is no problem in the other 2 cases, where the checkbox is not changed from the state in the DB).
How to solve this?
I initially thought the best way around this would be to test if there has been a validation error - if so, use the old()
value, with no default fallback; if not, use old()
with default fallback. One way to test for failed validation is to check $errors
. This seems to work, but it only works within a view AFAICT, as (from the Laravel docs):
Note: The $errors variable is bound to the view ...
I'd like to create a global helper for this, and $errors
won't work there. Anyway, this approach feels ... clunky and too complicated.
Am I missing something? Is there a neat Laravel way of solving this? It seems odd that old()
simply does not work for this particular case.
This is not a new problem, how do others handle this?
Upvotes: 2
Views: 4283
Reputation: 11
I came across the same problem and found this old post. Thought to share my solution:
<input type="checkbox" name="unicorns" class="form-check-input" id="verified" {{ !old()?$model->unicorns:old('unicorns')?' checked':'' }}>
{{ !old()?$model->unicorns:old('unicorns')?' checked':'' }}
Nested ternaries: The first ternary provides the condition for the second:
When there is no old()
array, there is no post, thus the DB value $model->unicorns
will be used as the condition like so:
{{ $model->unicorns?' checked':'' }}
will correctly evaluate on a value of either 0 or 1
If however old()
array is present, we can use the existence of the old('unicorns')
variable as the condition like so:
{{ old('unicorns')?' checked':'' }}
will correctly evaluate on a value of on
or no value.
It's a bit of type juggle and you have the nested ternary, but it works well.
Upvotes: 1
Reputation: 569
I do this
<input id="main" class="form-check-inline"
type="checkbox" name="position" {{old('position',$position->status)?'checked':''}}>
Upvotes: 0
Reputation: 14520
This is the solution I referred to in my question. It works well, and 6 months later, it does not seem as clunky as when I posted the question. I'd be happy to hear how others are doing this though.
I have an Html
helper, created as described in this question, and aliased in config/app.php
as described in the first part of this answer to that question. I added a static method to it:
namespace App\Helpers;
use Illuminate\Support\ViewErrorBag;
class Html {
/**
* Shortcut for populating checkbox state on forms.
*
* If there are failed validation errors, we should use the old() state
* of the checkbox, ignoring the current DB state of the field; otherwise
* just use the DB value.
*
* @param string $name The input field name
* @param string $value The current DB value
* @return string 'checked' or null;
*/
public static function checked($name, $value) {
$errors = session('errors');
if (isset($errors) && $errors instanceof ViewErrorBag && $errors->any()) {
return old($name) ? 'checked' : '';
}
return ($value) ? 'checked' : '';
}
}
Now in my views I can use it like so:
<input type='checkbox' name='unicorns' value='1' {{ \Html::checked('unicorns', $model->unicorns) }}>
This correctly handles all combinations of DB and submitted state, on initial load and after failed validation.
Upvotes: 1
Reputation: 201
From Don't Panic 's answer, you could do it like this in blade:
<input type="checkbox" class="form-check-input" value='true'
@if ($errors->any())
{{ old('is_private') ? 'checked' : '' }}
@else
{{ isset($post) && $post->is_private ? 'checked' : '' }}
@endif
>
Hope it helps.
Upvotes: 0
Reputation: 2130
I had a similar situation and my solution was to add a hidden field just before the checkbox field. So, in your case it would be something like:
<input type='hidden' name='unicorns' value='0'>
<input type='checkbox' name='unicorns' value='1' {!! old('unicorns', $model->unicorns) ? ' checked' : '' !!}>
That way, when the checkbox is not ticked, a value of 0 for that field will still be present in the post request. When it is ticked then the value of the checkbox will overwrite the value in the hidden field, so the order is important. You shouldn't need to use your custom class with this approach.
Does that work for you?
Upvotes: 0
Reputation: 1684
I actually do a simple ternary operator when persisting checkbox states:
<input name='remember' type='checkbox' value='1' {{ old('remember') ? 'checked' : '' }}>
Edit:
<input name='remember' type='checkbox' value='yes' {{ old('remember') == 'yes' ? 'checked' : '' }}>
Upvotes: -1