0

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

学生控制器

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));  
   }
}
4

2 回答 2

2

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

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

阅读 CakePHP 中的数据验证

于 2012-02-01T10:10:12.540 回答
0

德塞兹和查普曼是对的。我从 cakephp 食谱的数据验证章节中找到了解决方案。非常感谢你们。

以下是我添加的验证规则:

对于学生模型中的学生姓名:

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!'
                     )
                ),

然后在StudentController的add函数中:

//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         
}       
于 2012-02-02T06:47:59.823 回答