2012-02-01 67 views
0

我在学生模型中有这个beforeSave方法,它返回true或false。 而不是显示学生控制器中的所有保存错误的标准味精(您的录取无法保存,请再试一次。),我想在学生模型的beforeSave mtd返回false时显示不同的错误消息。我怎样才能做到这一点?cakephp:在模型的beforeSave方法返回false时在控制器中显示错误消息?

StudentsController

function add(){ 
if ($this->Student->saveAll($this->data)){ 
$this->Session->setFlash('Your child\'s admission has been received. We will send you an email shortly.'); 
}else{ 
$this->Session->setFlash(__('Your admission could not be saved. Please, try again.', true)); 
    } 
} 
+0

*为什么* beforeSave'返回'false'? – deceze 2012-02-01 05:28:01

+0

beforeSave返回false以避免将重复记录插入数据库表中。 – vaanipala 2012-02-01 06:38:34

+4

然后,您应该能够使用自动错误消息而不是“beforeFilter”操作将其作为常规验证规则实施。这将产生定期的,很好的错误消息。 – deceze 2012-02-01 07:17:58

回答

2

我建议实施验证规则,然后调用:

if ($this->Model->validates()) { 
    save 
} else { 
    error message/redirect 
} 

内CakePHP的

阅读上的数据验证
+0

好的,我会阅读数据验证并回复给您。谢谢。 – vaanipala 2012-02-02 04:55:48

0

Deceze查普曼是正确的。我从cakephp cookbook的DAta验证章节找到了解决方案。非常感谢你们。

以下是验证规则我已经加入:以学生在学生型号名称

var $validate=array(
     'name'=>array(
       'nameRule1'=>array(
        'rule'=>array('minLength',3), 
        'required'=>true, 
        'allowEmpty'=>false, 
        'message'=>'Name is required!' 
        ), 
       'nameRule2'=>array(
         'rule'=>'isUnique', 
         'message'=>'Student name with the same parent name already exist!' 
        ) 
       ), 

然后在StudentsController的附加功能:

//checking to see if parent already exist in merry_parents table when siblings or twin are admitted. 
      $merry_parent_id=$this->Student->MerryParent->getMerryParentId($this->data['MerryParent']['email']); 
      if (isset($merry_parent_id)){ 
       $this->data['Student']['merry_parent_id']=intval($merry_parent_id); 
       var_dump($this->data['Student']['merry_parent_id']); 
       if ($this->Student->save($this->data)){ 
       //data is saved only to Students table and not merry_parents table. 
        $this->Session->setFlash(__('Your child\'s admission has been received. 
             We will send you an email shortly.',true)); 
       }else 
         $this->Session->setFlash(__('Your admission could not be saved. Please, try again.',true)); 
      }else{//New record. So, data is saved to Students table and merry_parents table. 
         if ($this->Student->saveAll($this->data)){ //save to students table and merry_parents table 
         $this->Session->setFlash(__('Your child\'s admission has been received. 
                  We will send you an email shortly.',true)); 
         }else 
          $this->Session->setFlash(__('Your admission could not be saved. Please, try again.', true)); 
       }//new record end if 

没有必要对于我来说,查普曼提到的没有保存的数据是有效的。所以,我没有使用:

if ($this->Model->validates()) {   
    save   
} else {   
    error message/redirect   
}  
相关问题