0
我正在爲我的網站構建一個簡單的聯繫表單。CakePHP 2.2.1如何將驗證錯誤傳遞給SetFlash?
在我的模型,我有:
class Contact extends AppModel {
public $useTable = false;
public $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'Field name must be not empty'
),
'email' => 'email',
'message' => array(
'rule' => 'notEmpty',
'message' => 'Field message must be not empty'
)
);
}
控制器:
class ContactsController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
}
public function send() {
$this->Contact->set($this->request->data);
if ($this->Contact->validates()) {
//sending mail logic
};
} else {
// didn't validate logic
$errors = $this->Contact->validationErrors;
}
}
}
}
和index.ctp觀點,我有:
echo $this->Form->create('Contact', array('action' => 'send'));
echo $this->Form->input('name', array('label' => 'Your name:'));
echo $this->Form->input('email', array('label' => 'Your e-mail:'));
echo $this->Form->input('message', array('rows' => '6', 'label' => 'Your message:'));
echo $this->Form->end('Send button');
echo $this->Session->flash();
,因爲我使用的驗證數據從控制器我將$ errors傳遞給Session-> flash存在問題。什麼是適當的方式來做到這一點?我不想在控制器中爲「發送」方法制作額外的視圖。
嘗試使用架構進行更好的驗證並形成幫助器輸出:http://www.dereuromark.de/2011/12/15/tools-plugin-part-2-contact-form/ – mark 2012-08-01 18:19:09
@mark I don'不想使用插件。沒有工具插件可以實現我的目標嗎? – user1327 2012-08-01 19:04:13
你不必使用插件。只是拿出你需要的代碼(複製和粘貼)。還要注意,使用這種模式方法,您也不必將validationErrors傳遞給視圖。它會自動完成。所以我會說這是最乾淨的方法。 – mark 2012-08-01 19:13:29