4

I'm using Laravel 4.1 and in my app I need to show a form with pre filled checkboxes. But I try to do it with using Form Model Binding, it doesn't work.

{{ Form::model($user, array('route' => 'settings-notify')) }}

<div class="formRow form-horizontal_row">
    {{ Form::checkbox('notify_visit', '1') }}
</div>

<div class="formRow form-horizontal_row">
    {{ Form::checkbox('notify_rate', '1') }}
</div>


<div class="formSubmit">
   {{ Form::submit('Save') }}
</div>


{{ Form::close() }}

Is there any way to make it working?

2 Answers 2

6

I ended up handling this in my controller because as @Ladislav Maxa says in their comment to @Antonio Carlos Ribeiro the database never updates. This is because empty checkboxes are not submitted with the form so no 'unchecked' value is available for updating the database.

The solution I used is to check for the existence of the field in the get object. If it's there the box was checked.

$notify_rate = Input::get('notify_rate') ? 1 : 0;
$data['notify_rate'] = $notify_rate;

Another way I have done this before was to create a text input with the same name and a value of 0 before the checkbox. If the checkbox is unticked the text input value is submitted, if the checkbox is ticked it's value is used.

<input name="notify_rate" type="text" value="0">
<input name="notify_rate" type="checkbox" value="1">

That's probably not valid HTML though and I prefer dealing with this server side.

Sign up to request clarification or add additional context in comments.

1 Comment

In Laravel 4.2 unchecked inputs will never be submitted. Yes I resolved this issue the same way. I didn't try it in Laravel 5, but this could be totally handled in the framework. I'm assuming this is a bug. $model->show_name = 0; $model->show_phone = 0; $model->fill(Input::all());
2

Works fine for me, here's a test I just did here:

Route::get('test', function() {

    $user = User::where('email','[email protected]')->first();

    Form::model($user);

    $user->notify_rate = true;
    echo e(Form::checkbox('notify_rate'));

    $user->notify_rate = false;
    echo e(Form::checkbox('notify_rate'));

});

This is what I got:

<input checked="checked" name="notify_rate" type="checkbox" value="1">
<input name="notify_rate" type="checkbox" value="1">

1 Comment

You're right, it works. The problem in my app appears during the filling of model with new data and calling the save method. Although model has valid data, the database tuple representing form data is not overwritten.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.