cakephp 2.x表单验证,带模型但不带数据库

cakephp 2.x表单验证,带模型但不带数据库,cakephp,Cakephp,我对cakephp非常陌生,我尝试验证联系人表单。我需要在模型中没有数据库表的情况下进行验证。但它不起作用。我使用的代码如下所示 下面是代码:ContactsController.php <?php class ContactsController extends AppController { var $uses='Contact'; public function index() { // Placeholder for index. No actual

我对cakephp非常陌生,我尝试验证联系人表单。我需要在模型中没有数据库表的情况下进行验证。但它不起作用。我使用的代码如下所示

下面是代码:ContactsController.php

<?php
class ContactsController extends AppController {


  var $uses='Contact';

  public function index() {
        // Placeholder for index. No actual action here, everything is submitted to the send function.
    }

    public function send() {
            $this->Contact->set($this->data);
            if($this->Contact->validates()) {
       echo "hiiii";
}
        }




}
----------------------------Model-----------------------
<?php
App::uses('AppModel', 'Model');

class ContactModel extends AppModel {

    var $name = 'Contact';
    var $useTable = false;

    var $validate = array(
        'name' => array(
            'rule' => 'notEmpty',
            'required' => true
        ),
        'email' => array(
            'rule' => 'email',
            'required' => true
        ),
        'message' => array(
            'rule' => 'notEmpty',
            'required' => true
        )
    );
}
-----------------------in view/Contacts/index.ctp-----------------------------
<?php
echo $this->Form->create('Contact', array('action' => 'Contacts/send'));
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('message',array('rows' => 3));
echo $this->Form->submit('Submit');
?>

本文将为您提供所需的所有信息:


特别是如何使用_模式来构建验证和表单,这是一种简单的方法。

有一种方法可以在不使用模型的情况下进行验证,这种方法也可以用于表单,至少在CakePHP2中是这样

例如,我必须验证params,我认为为每个需要params的操作创建模型毫无意义

所以,我用了这个:

  • 在控制器类声明之前

    应用程序::使用('Validation','Utility')

  • 在带有$code参数的操作中

    函数检查码($code){ ... 验证::字母数字($code); ... }

  • $this->Contact->save()应从关联模型调用验证

    public function send() {
            $this->Contact->set($this->data);
            if($this->Contact->save()) {
              $this->Session->setFlash(__('Contact saved!'));
            }
    }
    

    如果条件中使用了validates(),请尝试使用else条件。在else条件下写入
    pr($this->Contact->invalidFields()),告诉发生了什么?在其他条件下重新写入pr($this->Contact->invalidFields());iArray([name]=>数组([0]=>此字段不能留空[1]=>此字段不能留空)[email]=>数组([0]=>此字段不能留空[1]=>此字段不能留空)[message]=>数组([0]=>此字段不能留空[1]=>此字段不能留空))我想你得到了所有要显示的结果。不是吗?