2014-02-10 48 views
0

我一直在学习如何使用CakePHP使用视频教程系列,并且我在表单上验证问题。我尝试了几个不同的东西,我在CakePHP书上找到了它,但它似乎也没有工作。这非常简单的验证,只是确保标题不是空的或重复的,并且该帖子不是空的,但表单仍然提交,无论它是空白还是重复。CakePHP表单验证不起作用

这里是我的模型:

class Post extends AppModel { 

    var $name = 'Post'; 
    var $validate = array(
     'title'=>array(
      'title_must_not_be_blank'=>array(
       'rule'=>'notEmpty', 
       'message'=>'This post is missing a title!' 
      ), 
      'title_must_be_unique'=>array(
       'rule'=>'isUnique', 
       'message'=>'A post with this title already exists!' 
      ) 
     ), 
     'body'=>array(
      'body_must_not_be_blank'=>array(
       'rule'=>'notEmpty', 
       'message'=>'This post is missing its body!' 
      ) 
     ) 
    ); 
} 

这里是控制器:

class PostsController extends AppController { 

    var $name = 'Posts'; 

    function index() { 
     $this->set('posts', $this->Post->find('all')); 
    } 

    function view($id = NULL) { 
     $this->set('post', $this->Post->read(NULL, $id)); 
    } 

    function add() { 
     if (!empty($this->request->data)) { 
      if($this->Post->save($this->request->data)) { 
       $this->Session->setFlash('The post was successfully added!'); 
       $this->redirect(array('action'=>'index')); 
      } else { 
       $this->Session->setFlash('The post was not saved... Please try again!'); 

      } 
     } 
    } 

    function edit($id = NULL) { 
     if(empty($this->data)) { 
      $this->data = $this->Post->read(NULL, $id); 
     } else { 
      if($this->Post->save($this->data)) { 
       $this->Session->setFlash('The post has been updated'); 
       $this->redirect(array('action'=>'view', $id)); 
      } 
     } 
    } 

    function delete($id = NULL) { 
     $this->Post->delete($id); 
     $this->Session->setFlash('The post has been deleted!'); 
     $this->redirect(array('action'=>'index')); 
    } 

} 

这里是视图:提前

<h2>Add a Post</h2> 
<?php 
echo $this->Form->create('Post', array('action'=>'add')); 
echo $this->Form->input('title'); 
echo $this->Form->input('body'); 
echo $this->Form->end('Create Post'); 
?> 

<p><?php echo $this->Html->link('Cancel', array('action'=>'index')); ?></p> 

谢谢!

+1

”但表单仍在提交“是正确的行为。提交后,验证在服务器端完成。你得到什么闪光信息? _post成功添加_1或_post未保存_一个? – arilia

+0

“该帖子已成功添加”。即使它们是空的和/或包含重复的标题,它也会将这些帖子添加到数据库中,这是我试图避免发生的事情。 –

回答

1

问题是您尝试使用的规则未在CakePHP框架中定义。如果你想要求的东西,并确保字段不为空,你应该试试这个:

'title' => array(
      'required' => array(
       'rule' => array('minLength', 1), 
       'allowEmpty' => false, 
       'message' => 'Please enter a title.' 
      )   
     ), 

'required'键告诉蛋糕,虽然'allowEmpty' => false告诉蛋糕的字段需要包含的东西,可以在现场要求只是一个空的字符串。 “