Модель проверки CakePHP всегда верна, но сообщения об ошибках все еще отображаются

Я пытаюсь проверить форму и сохранить в базе данных, но ItemType->validates() всегда имеет значение true, даже если я ввожу неверные данные.

ItemTypesController.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">

So, when I enter data in a form and submit, it always tries to save to a db, even though validation should not permit, I have debugged with debug() function, and $this->ItemType->validates() is always true. What makes it weirder, when I try to send same data but to debug error messages in the else block, they are present as they should be (but validates() is true):

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 имеют значение одновременно.


person Младен Карић    schedule 11.10.2019    source источник


Ответы (1)


Это происходит потому, что вы устанавливаете данные для проверки с помощью метода 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.'));
            }
        }
person ascsoftw    schedule 13.10.2019