我的Student模型中有这个beforeSave方法,返回true或false。 而不是在StudentsController中显示所有保存错误的标准消息(您的录取无法保存。请再试一次。),我想在学生模型的beforeSave mtd返回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 :(得分:2)
我建议实施验证规则然后调用:
if ($this->Model->validates() ) {
save
} else {
error message / redirect
}
阅读CakePHP中的数据验证
答案 1 :(得分:0)
Deceze和Chapman是对的。我从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
我没有必要像Chapman所提到的那样在没有保存的情况下验证数据。所以,我没有使用:
if ($this->Model->validates() ) {
save
} else {
error message / redirect
}