gpt4 book ai didi

php - CakePHP 提交表单时出现验证问题

转载 作者:行者123 更新时间:2023-11-29 04:12:12 24 4
gpt4 key购买 nike

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

如果这三个字段中的任何一个为空,它仍在将数据保存到表中。如果一个输入字段为空,我如何停止保存数据。但是comments表的列不为空。

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


}

最佳答案

在您的 Controller 中添加这些行,然后检查显示的错误是什么……我认为它会正常工作。如果字段为空,您提交表单时将显示错误

$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();


}

关于php - CakePHP 提交表单时出现验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com