CakePHP 2.1 Ajax validation errors

筅森魡賤 提交于 2019-12-04 21:05:24

In your controller you should have something like below. Cake 2.0 replaces many features in RequestHandlerComponent and Controller. It also replaces $this->params array in all places and the old $this->data to $this->request->data, something like that. You can visit the migration guide.

    public function validate_form(){
        if($this->RequestHandler->isAjax()){
           $this->request->data['Contact'][$this->request['form']['field']] = $this->request['form']['value'];
           $this->Contact->set($this->request->data);
           if($this->Contact->validates()){
              $this->autorender = FALSE; // don't render a view
           }else{
             $error = $this->validateErrors($this->Contact);
             // didn't validate logic
             $this->set('error',$this->Contact->validationErrors[$this->request['data']['field']][0]);
          }
       }
    }

Try $this->request->params['field'] instead of $this->request->params['form']['field'].

Or right after you check to isAjax(), try doing a var_dump on $this->request->params. From the error you are getting, the form index does not exist in $this->request->params.

If you want to simulate a POST like done when using a standard form and the Cake FormHelper, you could also simply name the posted parameters the same way the FormHelper names the input fields.

$j.post(
    '/Cake_ajax/Contacts/validate_form',
    { "data[Contact][" + $(this).attr('id') + "]": $(this).val() },
    handleNameValidation
);

This would automatically populate $this->request->data['Contact']['name'] and you could just comment this line:

//$this->request->data['Contact'][$this->request->params['form']['field']] = $this->request->params['form']['value'];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!