CakePHP только одна модель получает подтверждение - PullRequest
0 голосов
/ 29 февраля 2012

У меня есть форма, которую можно сохранить на две модели. В контроллере я называю валидацию. Но это проверяет только первую модель. Это сохранит без проверки второго.

Хорошо сохраняет обе модели. Не могу понять, что не так, я сначала использовал валидацию, как рекомендовано.

Контроллер:

        if ($this->Company->saveAll($this->request->data, array('validate'=>'first'))) {  // Should ensure both sets of model data get validated
            $this->Session->setFlash(__('The company has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The company could not be saved. Please, try again.'));
        }
    }

Вид:

    echo $this->Form->input('name');
    echo $this->Form->input('address1');
    echo $this->Form->input('address2');


    echo $this->Form->input('Umuser.username');
    echo $this->Form->input('Umuser.password');

первая модель:

/**
* Display field
*
* @var string
*/
public $displayField = 'name';
var $actsAs = array('Containable');
/**
* Validation rules
*
* @var array
*/
public $validate = array(
    'neci_member_number' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'numeric' => array(
            'rule' => array('numeric'),
            'message' => 'Members number should only contain numbers',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'length' => array(
            'rule' => array('maxLength', 11),
            'message' => 'No more than 11 digits',
        ),
    ),

    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'address1' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'address2' => array(
    ),
    'county' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'limited' => array(
        'boolean' => array(
            'rule' => array('boolean'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'tax_number' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'contact_name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'phone' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'numeric' => array(
            'rule' => array('alphanumeric'),
            'message' => 'Phone number should only contain numbers, no spaces or other characters',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'email' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),                  
        'email' => array(
            'rule' => array('email'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'payment_start' => array(
        'date' => array(
            'rule' => array('date'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
);

//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
    'Employee' => array(
        'className' => 'Employee',
        'foreignKey' => 'company_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
    'MonthlyReturn' => array(
        'className' => 'MonthlyReturn',
        'foreignKey' => 'company_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

public $hasOne = 'Umuser';

Вторая модель: Umuser расширяет класс UserminAppModel {

public function beforeSave() {

    if (isset($this->data[$this->alias]['password'])) {

        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

/**
 * Validation rules
 *
 * @var array
 */
public $validate = array(
    "username" => array(
        'mustUnique' => array(
            'rule' => array('isUnique'),
            'message' => 'That username is already taken.'),
        'mustBeLonger' => array(
            'rule' => array('minLength', 3),
            'message' => 'Username is required and must have a minimum of 3 alphanumeric characters.',
            'last' => true),
    ),
    'email' => array(
        'mustBeEmail' => array(
// code borrowed from here http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// thanks to James Watts and Francisco Jose Martin Moreno
            'rule' => '/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i',
// end of borrowed code
            'message' => 'Please supply a valid email address.',
            'last' => true),
        'mustUnique' => array(
            'rule' => 'isUnique',
            'message' => 'That email is already registered.',
        )
    ),
    'confirm_password' => array(
        'mustBeLonger' => array(
            'rule' => array('minLength', 4),
            'message' => 'Your password is too short, please provide 4 characters minimum.',
        ),
        'mustMatch' => array(
            'rule' => array('verifies', 'password'),
            'message' => 'You must fill in the password field and must match with confirm.'
        )
    ),
    'captcha' => array(
        'rule' => 'notEmpty',
        'message' => 'This field cannot be left blank'
    )
);

//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
public $belongsTo = array(
    'Company'=> array(
        'className' => 'Company',
        'foreignKey' => 'company_id'
        ),
    'Umrole' => array(
        'className' => 'Umrole',
        'foreignKey' => 'umrole_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

1 Ответ

1 голос
/ 29 февраля 2012

если вы используете AuthComponent, отправленные пароли будут автоматически хешироваться.Это может объяснить, почему вы видите эти точки при перезагрузке формы (вероятно, 40 точек между прочим).Что вы можете сделать, это указать, что вы хотите, чтобы поле пароля оставалось пустым:

    echo $this->Form->input('password', array(
        'label' => 'password',
        'value' => ''
    ));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...