Jeff P.
Jeff P.

Reputation: 3004

Laravel 4 PHP: Editing a form with 'unchecked' checkboxes produces an 'undefined index' error

I have an edit form containing several checkboxes. When I try to update the form with any of the checkboxes left 'unchecked', I get an "undefined index" error for that particular checkbox. When I initially store new data, 'unchecked' checkboxes are stored just fine. It's only an issue if I try to edit data and leave checkboxes 'unchecked'.

I've tried using the '{{Form::hidden(fieldname, 0) }}' method but it hasn't been working for me.

edit-album.blade.php(View):

{{ Form::model($album, array('method' => 'PUT', 'route' => array('edit_album2', $album->album_id))) }}

<div class ="form-group">

    {{ Form::checkbox('album_application_kitchen', 'Kitchen') }}
    {{ Form::label('album_application_kitchen', 'Kitchen') }}
    {{ Form::checkbox('album_application_bathroom', 'Bathroom') }}
    {{ Form::label('album_application_bathroom', 'Bathroom') }}<br />

</div>

{{ Form::close() }}

EditAlbumsController2.php(Controller):

public function update($id) {

$input = \Input::all();

$validation = new Validators\Album($input);

    if ($validation->passes())
    {
      $album = Album::find($id);
      $album->album_application_kitchen = $input['album_application_kitchen'];  
      $album->album_application_bathroom = $input['album_application_bathroom'];
      $album->touch();
      $album->save();

      return \Redirect::route('gallery.album.show', array('id' => $id));
    }
    else
    {
      /* Code for when validation fails */
    }
}

Is there a special trick to solve this problem or am I just not using the {{Form::hidden()}} structure properly?

Upvotes: 0

Views: 702

Answers (2)

mohaddese abbasi
mohaddese abbasi

Reputation: 89

I've had the same problem. I solved it with using the isset function.

if(isset($data['checkbox']))

Upvotes: -1

damiani
damiani

Reputation: 7371

In your controller, when you assign Input::all() to $input, no element gets added to the $input array for unchecked checkboxes, because they don't exist in the Input::all() array (unchecked checkboxes don't get passed in POST.) When updating, use Input::get() instead, which will return null if there is no value for an input, as is the case with any unchecked checkboxes:

$album->album_application_kitchen = Input::get('album_application_kitchen');  
$album->album_application_bathroom = Input::get('album_application_bathroom');

Besides, $input = Input::all() is redundant anyway, since Input::all() is already an array. Just pass Input::all() to your validator.

Upvotes: 4

Related Questions