0

这是我的模型-->

<?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.');
            }
        }
    }

并查看 -->

<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.org 上提供的 cakephp 书,做的和那里提到的完全一样,然后也做错了

4

2 回答 2

0

在创建刚刚从控制器设置和验证的记录之前

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.');
                 }

            }
  }
于 2013-05-16T12:42:55.933 回答
0

尝试使用更详细的数组声明:

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)。

于 2013-05-16T11:39:45.100 回答