Понимание того, когда работают правила $ validate модели - PullRequest
0 голосов
/ 05 января 2012

Я пытаюсь активировать пользователя с помощью CakePHP 2 по URL-адресу активации, но на странице регистрации пользователя появляется ошибка проверки.

Я создал действие регистрации и просмотр, где я определил UserModel правила проверки:

<?php
class User extends AppModel {
    public $name = 'User';

    public $validate = array (
        'username' => array (
            'not_empty' => array (
                'rule' => 'notEmpty',
                'message' => 'Username cannot be empty'
            )
        ), 
        'password' => array (
            'not_empty' => array (
                'rule' => 'notEmpty',
                'message' => 'Password cannot be empty'
            ),
            'between_chars' => array (
                'rule' => array ('between', 5, 40),
                'message' => 'Password must be between 5 and 40 chars'
            ),
            'match_password' => array (
                'rule' => 'matchPasswords',
                'message' => 'Password is different from Password confirm'
            )
        ),
        'password_confirm' => array (
            'not_empty' => array (
                'rule' => 'notEmpty',
                'message' => 'Password confirm cannot be empty'
            ),
            'between_chars' => array (
                'rule' => array ('between', 5, 40),
                'message' => 'Password confirm must be between 5 and 40 chars'
            )
        ),
        'email' => array (
            'invalid_email' => array (
                'rule' => 'email',
                'message' => 'Invalid email, try again'
            ),
            'existing_email' => array (
                'rule' => 'isUnique',
                'message' => 'This email is already registered'
            )
        ),
        'activation_key' => array (
            'alphanumeric_key' => array(
                'allowEmpty' => true,
                'rule' => 'alphaNumeric',
                'message' => 'Invalid activation key',
                'last' => true
            )
        )
    );


    public function matchPasswords ($data) {
        debug($this->data); // Undefined index: password_confirm [APP/Model/User.php, line 59] points here
        if ($data['password'] == $this->data['User']['password_confirm']) {
            return true;
        }
        $this->invalidate('password_confirm', 'Password confirm must be equal to Password field');
        return false;
    }

    public function beforeSave () {
        if (isset($this->data['User']['password'])) {
            $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }
}
?>

Все работает идеально, пока я не достигну действия activate UsersController с кодом активации, здесь я получаю Undefined index: password_confirm [APP/Model/User.php, line 59], который указывает на matchPasswords правила проверки User Model.

<?php

App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {
    public $name = 'Users';

    public function index () {
        $this->User->recursive = 0;
        $this->set('users', $this->User->find('all'));
    }

    public function view ($id = null) {
        if (!$id) {
            $this->Session->setFlash('Invalid user');
            $this->redirect(array('action'=>'index'));
        }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException('Invalid user');
        }
        $this->set('user', $this->User->read());
    }
    public function edit () {

    }

    public function delete () {

    }

    public function register () {
        // code for user registration
    }

    public function registration ($sub_action = null) {

    }

    public function password ($sub_action = null, $code = null) {
        if ($sub_action == 'reset' && !empty ($code)) {
            $this->render('password_reset_code');
        } else if ($sub_action == 'reset' && empty ($code)) {
            $this->render('password_reset_mail');
        }
    }

    public function login () {

        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect ($this->Auth->redirect());
            } else {
                $this->Session->setFlash('Errore di accesso, email/password sbagliati, ricontrolla i dati inseriti');
            }
        }
    }

    public function logout () {
        $this->redirect($this->Auth->logout());
    }

    public function activate ($code = null) {
        if (!empty ($code)) {

            $user = $this->User->find('first', array('conditions' => array('User.activation_key' => $code)));

            if (!empty($user)) {
                $user['User']['activation_key'] = null;
                $user['User']['active'] = 1;


                if ($this->User->save($user)) { // here is where Invalid index error starts
                    $this->render('activation_successful');
                } else {
                    $this->set('status', 'Salvataggio fallito');
                    $this->render('activation_fail');
                }
                // debug($this->User->invalidFields());
                // debug($this->User->data);

            } else {
                $this->set('status', 'Nessun account collegato alla chiave');
                $this->render('activation_fail');
            }
        } else {
            $this->set('status', 'Nessuna chiave');
            $this->render('activation_fail');
        }
    }

    private function registrationEmail ($account_email, $username, $code) {
        // code for email registration
    }
}
?>

Почему я получаю ошибку?
Почему matchPasswords выполняется в действии activate?
Эти правила проверки выполняются в каждом представлении контроллера?

Ответы [ 2 ]

0 голосов
/ 07 января 2012

Попробуйте изменить

if ($data['password'] == $this->data['User']['password_confirm']) {

до

if (isset($this->data['User']['password_confirm']) && $data['password'] == $this->data['User']['password_confirm']) {

в вашей функции matchPasswords в User.php

В действии активации вы получаете все поля для пользователя, а затем сохраняете их, чтобы в данных, которые вы сохраняете, было поле пароля. Поскольку поле пароля есть, CakePHP пытается проверить его по полю password_confirm, которое не существует.

Вы должны проверять, совпадают ли поля ввода пароля и подтверждения пароля, когда они оба присутствуют, т. Е. Когда в вашей форме есть password_confirm.

0 голосов
/ 06 января 2012

Попробуйте установить идентификатор модели пользователя перед сохранением в функции activ ():

$this->User->id = $user['User']['id'];

или что-то подобное.

Когда вы не устанавливаете идентификатор до сохранения(), она пытается создать новую строку таблицы.Вот почему все проверяется.

...