echo $this->Form->create('Comment',
array('url'=>array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']) )
);
echo $this->Form->input('post_id',array('type'=>'hidden','style'=>'width:30%','value'=>$listposts['Post']['id']));
echo $this->Form->input('name',array('style'=>'width:30%'));
echo $this->Form->input('email',array('style'=>'width:30%'));
echo $this->Form->input('body',array('rows'=>'5'));
echo $this->Form->end('Submit');
如果这三个字段中的任何一个为空,它仍然将数据保存到表中。如果一个输入字段为空,如何停止保存数据。但是注释表的列不为空。
mysql> describe comments;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| post_id | int(11) | NO | MUL | NULL | |
| name | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | | NULL | |
| body | varchar(500) | NO | | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
评论模型=>
<?php
class Comment extends AppModel {
var $useTable='comments';
var $belongsTo = array('Post');
}
带有验证的模型但它没有显示任何消息,但它不保存数据。
post<?php
class Comment extends AppModel {
var $useTable='comments';
var $belongsTo = array('Post');
var $validate = array(
'name' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Name.'
),
'email' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Email.'
),
'body' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Body.'
)
);
}
答案 0 :(得分:4)
在你的控制器中添加这些行,然后检查显示的错误是什么..我认为它会正常工作。使用空字段提交表单错误将显示
$this->Comment->set($this->data);
if ($this->Comment->validates())
{
if ($this->Comment->save($this->data))
{
$this->Session->setFlash('Comment saved ', 'default'));
}
else
{
var_dump($this->Comment->invalidFields());
//OR
$this->Comment->validationErrors();
}
}
else
{
var_dump($this->Comment->invalidFields());
//OR
$this->Comment->validationErrors();
}
答案 1 :(得分:2)
更改模型
<?php
class Comment extends AppModel {
var $useTable='comments';
var $belongsTo = array('Post');
var $validate = array(
'name' => array(
'rule' => array('maxLength' , 80),
'required' => true,
'message' => 'Please enter your name'
),
'body' => array(
'rule' => array('maxLength' , 80),
'required' => true,
'message' => 'Please enter your body'
),
'email' => array(
'rule' => 'email',
'required' => true,
'message' => 'Please enter a valid email address.'
),
);
}
?>