【问题标题】:Laravel saving post variable when there is validation error?出现验证错误时,Laravel 会保存 post 变量吗?
【发布时间】:2014-04-25 02:39:58
【问题描述】:

我正在使用 laravel 4,并且我有一个带有复选框的表单,并且在提交表单时,它会通过验证错误过程,如果有错误,我如何让它保存这些复选框的帖子值?

AdminRolesController:

     public function postActions($action = NULL) {

  // Allowed post actions..
  $allowed = array('add', 'edit');
  $action = in_array($action, $allowed) ? $action : NULL; 

  // check if action is not null
  if(is_null($action))
   return Redirect::to('admin/roles');

  else
  {
         // POST ACTION
           if($action == "add")
            {                 
               // put all your rules.
               $rules = array(
                'name'=>'required|regex:/^[a-zA-Z ]*$/|min:2',
                'permission_ids' =>'required'
                );


                // run the validation rules on the inputs from the form
                $validator = Validator::make(Input::all(), $rules); 
                // get all permissions or groups available
                $perms = Permissions::all();

                // share it to the view
                // we have two parts of permissions ( 0 , 1) 
                // 0 : Admin Group Pages , 1: Front End Pages

                View::share('perms', $perms);

                    if ($validator->passes()) 
                    {
                        // validation has passed, save user in DB
                        // create instance of our model..
                        // create a new role
                          $role = new Role;
                          $role->name = Input::get('name');
                          $permission_ids = Input::get('permission_ids');


                          // save info to db.
                          $role->save();

                         $msg = 'Role '.$role->name.' has been added'; 
                    }// end validation if
                    else 
                    {
                    // validation has failed, display error messages 
                    return Redirect::back()->with('message', 'The following errors occurred:')->withErrors($validator)->withInput();  
                    }

            }// end if add

   }
 }

我认为部分问题是我重定向错误消息,所有帖子值都丢失了,我怎么还能保留它们?

谢谢

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    您的控制器看起来不错 - 将输入传递回视图所需要做的就是链接 ->withInput()

    但是,在您的视图中,请确保您使用旧输入值填充表单。您可以使用 Blade 执行以下操作:

    {{ Form::checkbox('permission_id', 'value', Input::old('permission_id)) }}
    

    【讨论】:

    • 但我没有用户名?我有 permission_ids 作为复选框中的数组
    • 我更新了我的答案 - 我之前的只是一个例子。基本上,只需将表单中复选框的值设置为 Input::old('name_of_checkbox')
    • 如果我有多个复选框,我可以将其设为一个数组吗?比如:{{ Form::checkbox('permission_id[]', 'value', Input::old('permission_id)) }}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2023-04-03
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    相关资源
    最近更新 更多