Laravel 4 PHP:使用';未选中';复选框会生成一个';未定义索引';错误


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

我有一个包含多个复选框的编辑表单。当我尝试在任何复选框保持"未选中"的情况下更新表单时,我会收到该特定复选框的"未定义索引"错误。当我最初存储新数据时,"未选中"复选框存储得很好。只有当我试图编辑数据并将复选框保留为"未选中"时,这才是一个问题。

我尝试过使用"{{Form::hidden(fieldname,0)}}"方法,但它对我不起作用。

编辑相簿.blade.php(视图):

{{ 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(控制器):

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 */
    }
}

有没有解决这个问题的特殊技巧,或者我只是没有正确使用{{Form::hidden()}}结构?

在您的控制器中,当您将Input::all()分配给$input时,不会向未选中复选框的$input数组中添加任何元素,因为它们不存在于Input::all()数组中(未选中复选复选框不会在POST中传递。)更新时,请改用Input::get(),如果输入没有值,它将返回null,就像任何未选中复选盒的情况一样:

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

此外,$input = Input::all()无论如何都是冗余的,因为Input::all()已经是一个数组了。只需将Input::all()传递给您的验证器。

我也遇到过同样的问题。我用isset函数解决了这个问题。

if(isset($data['checkbox']))
相关文章: