Laravel表单请求更改回发中的所有隐藏输入

时间:2015-12-05 20:21:42

标签: validation laravel-5.1

我在一个页面上有以下两种形式:

 {!! Form::model($user, ['method' => 'PATCH', 'action' => ['AccountController@update']]) !!}
    {!! Form::hidden('action', 'personal-details') !!}
    <div class="form-group">
        {!! Form::label('name', 'Name', ['class' => 'h4']) !!}
        {!! Form::text('name', null, ['class' => 'form-control']) !!}
        {!! errors_for('name', $errors) !!}
    </div>
    <div>
           <button type="submit" class="btn btn-primary">Update personal details</button>
    </div >
{!! Form::close() !!}

{!! Form::model($user, ['method' => 'PATCH', 'action' => ['AccountController@update']]) !!}
    {!! Form::hidden('action', 'email') !!}
    <div class="form-group">
         {!! Form::label('new_email', 'New email address') !!}
         {!! Form::email('new_email', Input::old('new_email'), ['class' => 'form-control']) !!}
         {!! errors_for('new_email', $errors) !!}
    </div>
    <div>
           <button type="submit" class="btn btn-primary">Update email address</button>
    </div >
{!! Form::close() !!}

这是我处理验证的表单请求:

class AccountRequest extends Request
{
    protected $action;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $rules = [];
        $this->action = $this->input('action');

        if ($this->action == 'personal-details') {
            $rules['name'] = 'required|max:255';
        }

        if ($this->action == 'email') {
           $rules['new_email'] = 'required|confirmed|email|max:255|unique:users,email';
        }


        return $rules;
    }


    public function response(array $errors)
    {
        if ($this->ajax() || $this->wantsJson()) {
            return new JsonResponse($errors, 422);
        }

        return $this->redirector->to($this->getRedirectUrl() . '#'. $this->action)
            ->withInput($this->except($this->dontFlash))
            ->withErrors($errors, $this->errorBag);
    }

}

如果存在验证错误,则在回发时,两个表单上的隐藏字段将被设置为隐藏字段值在原始发布表单上的内容。例如。如果我提交个人详细信息表单,则在回发时,两个表单上的操作字段的值将设置为personal-details。如果我提交电子邮件表单,在回发后,两个表单上的隐藏字段将设置为email。为什么会发生这种情况?如何解决这个问题,以便在回发时隐藏的字段值不会改变?

1 个答案:

答案 0 :(得分:0)

通过在响应方法的开头添加以下内容来管理以修复它:

$this->dontFlash[] = 'action';