我一直在学习如何使用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>
提前致谢!
答案 0 :(得分:1)
问题是您尝试使用的规则未在CakePHP框架中定义。如果你想要一些东西并确保该字段不是空的,你应该试试这个:
'title' => array(
'required' => array(
'rule' => array('minLength', 1),
'allowEmpty' => false,
'message' => 'Please enter a title.'
)
),
'required'
键告诉Cake该字段是必需的,而'allowEmpty' => false
告诉Cake该字段需要包含某些内容而不能只是一个空字符串。