我正在尝试使用cakephp模型实现表单验证。这是我的代码片段......
模型
// File: /app/models/enquiry.php
class Enquiry extends AppModel {
var $name = "Enquiry";
var $useTable = false;
var $_schema = array(
"name" => array( "type" => "string", "length" => 100 ),
"phone" => array( "type" => "string", "length" => 30 ),
"email" => array( "type" => "string", "length" => 255 )
);
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Name is required'
),
'email' => array(
'emailFormat' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Email is required'
),
'emailNeeded' => array(
'rule' => array('email', true),
'required' => true,
'message' => 'Must be a valid email address'
)
)
);
}
控制器操作
// /app/controllers/nodes_controller.php
class NodesController extends AppController {
var $name = "Nodes";
var $uses = array( "Enquiry" );
function enquire() {
if ( $this->data ) {
$this->Enquiry->set( $this->data );
if ( $this->Enquiry->validates() ) {
// .....
} else {
$this->set("errors", $this->Enquiry->invalidFields());
}
}
}
}
查看...
// /app/views/nodes/enquire.ctp
<?php echo $form->create("Node", array("action" => "ask")); ?>
<?php echo $form->input("name", array(
"error" => array( "class" => "error-message" ),
"div" => false,
"label" => "Name",
"size" => "40"
) ); ?>
<?php echo $form->input("email", array(
"error" => array( "class" => "error-message" ),
"div" => false,
"label" => "Email",
"size" => "40"
) ); ?>
<?php echo $form->input("phone", array(
"label" => "Phone No.",
"div" => false,
"size" => "30"
) ); ?>
<?php echo $form->end("Send");?>
我的问题:在提交时,表单验证发生,Model-&gt; validates方法返回false,但验证错误永远不会显示。我检查了invalidFields()返回的数组,我在模型中设置的所有错误消息都在那里,但它们没有显示....
我做错了什么?
此致
答案 0 :(得分:1)
对我来说,问题出在你的表格标签上。
基本上,如果您验证查询,公司字段应具有以下名称:data [Inquiry] [name]而不是data [Node] [name]。
如果你改变了
<?php echo $form->create("Node", array("action" => "ask")); ?>
到
<?php echo $form->create("Enquiry", array("action" => "ask")); ?>
错误应该出现在核心。
如果您的表单混合了Node和Inquiry字段,那么只需将Model的名称放在字段名称前面,如下所示:
<?php echo $form->input("Enquiry.email", array(....));?>