說明如何使用CakePHP的模型驗證消息而不是控制器的setFlash消息?
我有我的網站的每個網頁上的一個簡單的形式 - 一個輸入和一個提交按鈕。這一點只是讓用戶輸入他/她的電子郵件地址並點擊提交。
它適用於數據是電子郵件地址 - 但如果它不是一個有效的電子郵件地址,它提交表單,頁面重新加載(或其他),並且閃光消息出現,而不是我的模型更具體的「不有效的電子郵件「錯誤。
問:
那麼,我該如何使用,而不是控制器的一個通用模型的驗證消息?
形式:
echo $this->Form->create('Email', array('class'=>'form1', 'url'=>'/emails/add', 'inputDefaults'=>array('label'=>false)));
echo $this->Form->input('Email.email');
echo $this->Form->end('SIGN-UP');
電子郵件控制器 「添加」 功能(或方法):
function add() {
if (!empty($this->data)) {
$this->Email->create();
if ($this->Email->save($this->data)) {
$this->Session->setFlash(__('The email address has been saved', true));
$this->redirect($this->referer());
} else {
$this->Session->setFlash(__('The email address could not be saved. Please, try again.', true));
$this->set('error', 'custom error here');
$this->redirect($this->referer());
}
}
}
和電子郵件型號:
class Email extends AppModel {
var $name = 'Email';
var $validate = array(
'email' => array(
'is_valid' => array(//named whatever we want
'rule' => 'notEmpty',
'rule' => array('email', true),
'message' => 'Please supply a valid email address.',
'last' => true //causes it to not check the next rule if this one fails
),
'is_unique' => array(//named whatever we want
'rule' => 'isUnique',
'message' => 'That email address is already in our database.'
)
),
);
}
對不起,我以前沒有看到。 雖然我不認爲你已經回答了我的問題 - 你的代碼似乎只是吐出「存在一個問題......」而不是模型驗證中的錯誤,這正是我所要求的。謝謝你的回答,如果我誤解了你的回答,請告訴我。 – Dave 2011-03-24 02:04:59
@Dave問題是即使在出現錯誤的情況下也會重定向,這會導致您丟失錯誤消息。如果您不**重定向,則錯誤消息將自動注入到表單中(只要您正確使用表單助手)。驗證消息不會在頁面刷新中持續存在。 – deceze 2011-03-24 04:14:53
ANSWER REWORDED(ty @Leo):Cake將Model驗證的錯誤放在.error-message div中,並且會出現在頁面上,除非您確實像我在我的問題中所做的那樣,即使在驗證失敗時也重定向頁面。 所以 - 任何人發現這個問題 - 只是不重定向頁面,如果它不保存。感謝Leo和YOMorales - 這兩個答案都很好 - 看起來這似乎一定是這樣做的預期方式。 – Dave 2011-03-24 05:04:28