这是我的模型->
<?php
class Post extends AppModel {
public $validate = array(
'title' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
?>
控制器——>
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
and view ->
<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>
我怎样才能让这个工作。我跟着cakephp的书他们在cakephp.org上提供的,做了完全相同的事情,不管那里提到什么,然后也无法得到正确的
尝试使用更详细的数组声明:
class Post extends AppModel {
public $validate = array(
'title' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
),
...
等(注意更深的数组结构),如文档(http://book.cakephp.org/2.0/en/models/data-validation.html)。
在创建记录之前,只需设置并验证控制器
public function add()
{
if ($this->request->is('post'))
{
$this->Post->create();
$this->Post->set($this->request->data['Post']); // Add this Line
if ($this->Post->validates()) // Add this Line
{
if ($this->Post->save($this->request->data))
{
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
}