I'm creating a checkbox in a view:
Form::checkbox('test', 'true', Input::old('test', true));
After unchecking the box, submitting the form and being redirected back:
return Redirect::back()->withInput()->withErrors($validation);
The checkbox is still checked - presumably because 'test'
doesn't exist in "Input::old"
so it is reverting back to the default value.
Any suggestions on how best to achieve this?
Edit:
I've come up with a somewhat hacky way of getting the results I want:
$isChecked = true; // The default state
// Check if the form has been returned "withInput"
if(Input::old())
{
$isChecked = Input::old('test', false); // If the field has old data available use that, otherwise it is unchecked
}
echo Form::checkbox('test', 'true', $isChecked);
I'll write this into a function for reuse, but it seems a bit painful so any comments/suggestions would be great
Edit 2 Sorry if not clear - to clarify:
I assume this happens because if a checkbox isn't checked the element isn't included in the post data
I had the same problem. Turns out it was because I followed the instructions on how to post an unchecked checkbox, which said:
echo Form::hidden('name', 0);
echo Form::checkbox('name', 1);
The problem with this is that on form validation fail, if the checkbox was checked, Laravel will repopulate both 'hidden' and 'checkbox' fields with old value, so your hidden field will always be submitting 1 instead of 0. Simple solution is just write HTML for the hidden field instead of using the form helper:
echo '<input type="hidden" name="name" value="0">';
echo Form::checkbox('name', 1);
This should is sufficient
echo Form::checkbox('test', 'true', Input::old('test', true));
If Input::old() doesn't exists, it will return true, your default.
The checkbox and session mismatch was an error that has been corrected in Laravel 4. The following code should preserve the checkbox on redirect:
echo Form::checkbox('payment_method', 'credit');
For grouped checkboxes, use something like this:
echo Form::checkbox('payment_method[]', 'credit');
That should also work.
**Obviously you will want to replace payment_method and credit with your own attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With