首页 > 解决方案 > CakePHP 验证模型始终为真,但仍然显示错误消息

问题描述

我正在尝试验证表单并保存到数据库,但 ItemType->validates() 始终为真,即使我输入了错误的数据。

项目类型控制器.php

<?php
App::uses('AppController', 'Controller');

class ItemTypesController extends AppController {

public function add() {
    if ($this->request->is('post')) {
        $this->ItemType->set($this->request->data);
        $this->ItemType->create();
        if($this->ItemType->validates()){
            debug($this->ItemType->validates());
            if ($this->ItemType->save($this->request->data)) {
                $this->Flash->success(__('The item type has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {

                $this->Flash->warning(__('The item type could not be saved. Please, try again.'));
            }
        }
        debug($this->ItemType->validationErrors);
        $this->Flash->warning($this->ItemType->validationErrors);

    }
}




}

项目类型.php

class ItemType extends AppModel {


public $validate = array(
    'code' => array(
        'required' => array(
            'rule' => 'notBlank',
            'message' => 'A code is required'
        ),
        'alphanum' => array(
            'rule' => 'alphanumeric',
            'message' => 'A code must be an alphanumeric value'
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This code already exists!'
        )
    ),
    'name' => array(
        'required' => array(
            'rule' => 'notBlank',
            'message' => 'A name is required'
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This name already exists!'
        )
    ),
    'class' => array(
        'valid' => array(
            'rule' => array('inList', array('product', 'material', 'kit', 'semi_product', 'service_product', 'service_supplier','consumable','inventory','goods','other')),
            'message' => 'Please enter a valid class',
            'allowEmpty' => false
        )
    ));

public $hasMany = array(
    'Item' => array(
        'className' => 'Item',
        'foreignKey' => 'item_type_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

}

添加.ctp

<div class="itemTypes form">
<?php echo $this->Form->create('ItemType'); ?>
<fieldset>
    <legend><?php echo __('Add Item Type'); ?></legend>
<?php
    echo $this->Form->input('code');
    echo $this->Form->input('name');
    echo $this->Form->input('class');
    echo $this->Form->input('tangible');
    echo $this->Form->input('active');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">

因此,当我在表单中输入数据并提交时,它总是尝试保存到数据库,即使验证不允许,我已经使用 debug() 函数进行了调试,并且 $this->ItemType->validates() 总是真的。更奇怪的是,当我尝试发送相同的数据但调试 else 块中的错误消息时,它们应该是存在的(但 validates() 是真的):

array(
'code' => array(
    (int) 0 => 'This code already exists!'
),
'name' => array(
    (int) 0 => 'A name is required'
),
'class' => array(
    (int) 0 => 'Please enter a valid class'
)
)

我不明白 $this->ItemType->validates 如何为真并且 $this->ItemType->validationErrors 同时具有价值。

标签: phpvalidationcakephpcakephp-2.x

解决方案


发生这种情况是因为您将数据设置为使用set方法进行验证,但在下一行您正在调用create. 该create方法会清除所有内容,因此您不会收到任何验证错误。根据文档

它实际上并没有在数据库中创建记录,而是清除 Model::$id 并根据您的数据库字段默认值设置 Model::$data。如果您没有为数据库字段定义默认值,则 Model::$data 将设置为空数组。

您需要将行移动$this->ItemType->create(); 到您的save方法之前。

您的代码应如下所示:

        $this->ItemType->set($this->request->data);
        //$this->ItemType->create();           //Commented this
        if($this->ItemType->validates()){
            debug($this->ItemType->validates());
            $this->ItemType->create();  //Move your create here.
            if ($this->ItemType->save($this->request->data)) {
                $this->Flash->success(__('The item type has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {

                $this->Flash->warning(__('The item type could not be saved. Please, try again.'));
            }
        }

推荐阅读