1

在验证为真之前,我将向控制器添加什么以显示消息并停止保存?

class Rsvp extends AppModel {
var $name = 'Rsvp';
var $validate = array(
                'uname' => array(
                                'rule' => array('alphaNumeric', true),
                                'message' => 'Please enter a vlaid name that does not contain digits'),
                'uemail' => array(
                                'rule' => array('email', true),
                                'message' => 'Please supply a valid email address.')


);

}

控制器

public function add() {


    if ($this->request->is('post')) {

        var_dump($this->request->data);
        $this->Rsvp->set('uname', $this->request->data['Post']['name']);
        $this->Rsvp->set('uemail', $this->request->data['Post']['emailaddress']);           
          //Begin Validation Routine
        echo 'Validation';
        var_dump($this->Rsvp->validates);


        $this->Rsvp->save();    
        /*if($this->Rsvp->save()) {
            $this->Session->setFlash('You have RSVP for the event');
           // $this->redirect(array('action' => 'index'));              
        }
        else {
            $this->Session->setFlash('Unable to RSVP you for the event.');
        }*/
    }
}
4

2 回答 2

2

你的意思是这样的:

if($this->Rsvp->validates()) {
   //data validated, so save
   $this->Rsvp->save($this->data);    
}
else {
   $this->Session->setFlash(__('Fill in all required fields.', true));
}
于 2012-05-03T11:52:04.200 回答
0

默认情况下,该Model::save()方法将自动验证。因此,只需尝试保存即可完成验证:

if ($this->request->is('post')) {
  if ($this->Rsvp->save($this->request->data)) {
    // validated and saved to db
  } else {
    // didn't validate or failed saving to db
  }
}

如果您不想验证,请使用

$this->Rsvp->save($this->request->data, array('validate' => false));

validates()最后,您可以通过设置数据并运行方法来手动验证。

$this->Rsvp->set('uname', $this->request->data['Post']['name']);
$this->Rsvp->set('uemail', $this->request->data['Post']['emailaddress']);
$validates = $this->Rsvp->validates();

如果它没有验证,它将设置$this->Rsvp->validationErrors,然后在控制器上设置它,表单助手将意识到这些错误并自动为您显示它们。

您可以在书中阅读有关保存数据和数据验证的更多信息:http: //book.cakephp.org/2.0/en/models/saving-your-data.html

于 2012-05-03T14:48:20.450 回答