Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unchecked checkbox with "Input::old()"

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:

  1. Form is loaded with checkbox checked
  2. I uncheck the checkbox and submit the form
  3. The form doesn't validate so I'm returned to the form
  4. The checkbox has re-checked itself - I would expect it to be unchecked, as per the user submitted data

I assume this happens because if a checkbox isn't checked the element isn't included in the post data

like image 708
Guy Incognito Avatar asked Jun 02 '13 15:06

Guy Incognito


3 Answers

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);
like image 74
GTCrais Avatar answered Nov 16 '22 20:11

GTCrais


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.

like image 5
Antonio Carlos Ribeiro Avatar answered Nov 16 '22 22:11

Antonio Carlos Ribeiro


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.

like image 2
kablamus Avatar answered Nov 16 '22 22:11

kablamus