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>
谢谢!
”但表单仍在提交“是正确的行为。提交后,验证在服务器端完成。你得到什么闪光信息? _post成功添加_1或_post未保存_一个? – arilia
“该帖子已成功添加”。即使它们是空的和/或包含重复的标题,它也会将这些帖子添加到数据库中,这是我试图避免发生的事情。 –