cakephp:当模型的beforeSave方法返回false时,在控制器中显示错误消息?
我的学生模型中有一个beforeSave方法,它返回true或false。 我希望在beforeSave mtd of Student model返回false时显示不同的错误消息,而不是在StudentsController中显示所有保存错误的标准消息(无法保存您的录取。请重试)。我该怎么做 学生控制员cakephp:当模型的beforeSave方法返回false时,在控制器中显示错误消息?,cakephp,before-save,Cakephp,Before Save,我的学生模型中有一个beforeSave方法,它返回true或false。 我希望在beforeSave mtd of Student model返回false时显示不同的错误消息,而不是在StudentsController中显示所有保存错误的标准消息(无法保存您的录取。请重试)。我该怎么做 学生控制员 function add(){ if ($this->Student->saveAll($this->data)){ $this->Session->setFla
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));
}
}
我建议实施验证规则,然后调用:
if ($this->Model->validates() ) {
save
} else {
error message / redirect
}
阅读CakePHP中的数据验证,Deceze和Chapman是正确的。我从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!'
)
),
然后在StudentsController的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
}
为什么
beforeSave
返回false
?beforeSave返回false以避免在db表中插入重复记录。然后,您应该能够通过自动错误消息而不是beforeFilter
操作将其作为常规验证规则来实现。这将产生常规的、良好的错误消息。好的,我将检查数据验证并让您知道。好的,我将阅读数据验证并返回给您。谢谢