Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3.x: how to edit a validation rule on the fly

I cannot figure out how to edit a validation rule on the fly, for example in my controller.

My case: the "users" table has the "email" field, whose value must be "unique" when creating and updating. For now it's ok, I have created the correct validation rules.

But now I have to create an action that allows users to recover their password. So there's a form in which users enter their email address and this form must be validated. After, the action checks if there's that email address and sends an email to reset the password.

So: I have to validate the form with the validation rules, but in this particular case I don't need the email is "unique".

How to change the validation rule only for one action?

Thanks.


EDIT

Maybe this?

class UsersTable extends Table {
    public function validationDefault(\Cake\Validation\Validator $validator) {    
        //Some rules...

        $validator->add('email', [
            'unique' => [
                'message'   => 'This value is already used',
                'provider'  => 'table',
                'rule'      => 'validateUnique'
            ]
        ]);

        //Some rules...

        return $validator;
    }

    public function validationOnlyCheck(\Cake\Validation\Validator $validator) {
        $validator->remove('email', 'unique');

        return $validator;
    }
}

In my action:

$user = $this->Users->newEntity($this->request->data(), [
    'validate' => 'OnlyCheck'
]);
like image 885
Mirko Pagliai Avatar asked May 09 '15 07:05

Mirko Pagliai


1 Answers

What you have in your question after your Edit is the intended way in which CakePHP 3 allows you to use different/dynamic validation rules per use case.

use Cake\Validation\Validator;
class UsersTable extends Table {
    public function validationDefault(Validator $validator) {    
        //Some rules...

        $validator->add('email', [
            'unique' => [
                'message'   => 'This value is already used',
                'provider'  => 'table',
                'rule'      => 'validateUnique'
            ]
        ]);

        //Some rules...

        return $validator;
    }

    public function validationOnlyCheck(Validator $validator) {
        $validator = $this->validationDefault($validator);
        $validator->remove('email', 'unique');
        return $validator;
    }
}

And then:

$user = $this->Users->newEntity($this->request->data(), [
    'validate' => 'OnlyCheck'
]);
like image 145
José Lorenzo Rodríguez Avatar answered Sep 19 '22 22:09

José Lorenzo Rodríguez