CakePHP - ошибки проверки отображаются дважды - PullRequest
1 голос
/ 15 октября 2019

Я использую CakePHP 2.10.19. У меня есть форма для ввода типов предметов. У меня также есть другие модели для ввода соответствующих объектов базы данных. Произошла ошибка: мои ошибки проверки дважды отображаются в этой форме. Для других форм это работает хорошо. Вот модель:

ItemType.php

App::uses('AppModel', 'Model');

class ItemType extends AppModel {

public $classes = array(
    'product' => 'Proizvod',
    'kit' => 'Kit (bundle)',
    'material' => 'Repromaterijal'
);

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!'
        ),
        'between' => array(
            'rule' => array('lengthBetween', 3, 7),
            'message' => 'Code must be between 3 and 7 characters long'
        )
    ),
    'name' => array(
        'required' => array(
            'rule' => 'notBlank',
            'message' => 'A name is required'
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This name already exists!'
        ),
        'between' => array(
            'rule' => array('lengthBetween', 3, 30),
            'message' => 'Name must be between 3 and 30 characters long'
        )
    ),
    '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
        )
    ),
    'tangible' => array(
        'bool' => array(
            'rule' => 'boolean',
            'message' => 'Incorrect value for the checkbox'
        )
    ),
    'active' => array(
        'bool' => array(
            'rule' => 'boolean',
            'message' => 'Incorrect value for the checkbox'
        )
    )
    );
public $hasMany = array(
    'Item' => array(
        'className' => 'Item',
        'foreignKey' => 'item_type_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);
}

ItemTypesController.php

<?php

class ItemTypesController extends AppController { 
    public function add() {
    if ($this->request->is('post')) {
        $this->ItemType->set($this->request->data);

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

                debug($this->ItemType->invalidFields());
                $this->Flash->error(__('The item type could not be saved. Please, try again.'));
            }
        }
        debug($this->ItemType->invalidFields());
        $this->Flash->warning($this->ItemType->validationErrors, array(
            'key' => 'negative'
        ));
    }
    $this->set('classes', $this->ItemType->classes);
}
}

Также отладка ($ this-> ItemType-> invalidFields ())показывает массив с двумя полями для каждого поля, например:

array(
'code' => array(
    (int) 0 => 'Code must be between 3 and 7 characters long',
    (int) 1 => 'Code must be between 3 and 7 characters long'
),
'name' => array(
    (int) 0 => 'Name must be between 3 and 30 characters long',
    (int) 1 => 'Name must be between 3 and 30 characters long'
)
)

... поэтому я предполагаю, что модель делает какую-то ошибку.

add.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', array('options' => $classes));
    echo $this->Form->input('tangible');
    echo $this->Form->input('active');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

У любого есть идея. Дело в том, что другие контроллеры имеют в основном ту же логику, но не имеют такой ошибки, когда ошибки проверки отображаются дважды.

Ответы [ 2 ]

1 голос
/ 15 октября 2019

Обычно это происходит потому, что проверка запускается дважды. Это срабатывает дважды, один раз, когда вы звоните $this->ItemType->validates()), и в другой раз, когда вы звоните debug($this->ItemType->invalidFields());

. Пожалуйста, прокомментируйте и удалите все операторы отладки.

0 голосов
/ 15 октября 2019

Очевидно, что после удаления операторов отладки все работает так, как должно, только с одной ошибкой проверки для каждого типа, как и должно быть. Не уверен, почему отладка сделала проблему, хотя.

...