dqjmq28248 2014-10-23 19:27
浏览 63
已采纳

Laravel 4 PHP:使用“未选中”复选框编辑表单会产生“未定义索引”错误

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?

  • 写回答

2条回答 默认 最新

  • doujiao1814 2014-10-23 20:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写