NoobieErrors
NoobieErrors

Reputation: 41

In CakePhp 4, how to specify unique constraint validator for multiple fields?

In my database i have this table:

table `candidates` (
      id,
      email,
      department
)

And both email and department need to be unique (you can apply for a post in two different departments with the same email but not twice in the same department with same email). This is built in my SQL DB.

And I am stuck as how to check this in CakePHP validators, because I can check for the uniqueness of two separate fields but not for the combination of two fields. It seemed to be possible in CakePHP2 like shown here https://book.cakephp.org/2/en/models/data-validation.html#Model::Validation::isUnique with this array method

public $validate = array(
    'email' => array(
        'rule' => array('isUnique', array('email', 'username'), false),
        'message' => 'This username & email combination has already been used.'
    )
);

But now validators work differently and I can't seem to find a way to solve this issue.

EDIT :

Here is what I have that doesn't work.

    public function validationDefault(Validator $validator): Validator
    {
        ...

        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmptyString('email')
            ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        return $validator;
    }

    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['email', 'vac_no']), 'This email has already been used for this vacancy');
        return $rules;
    }

Thanks

Sims Olden

Upvotes: 3

Views: 1351

Answers (1)

Wim Boogaart
Wim Boogaart

Reputation: 31

From cakephp 4.2 this is where you are looking for: Code example in a UsersTable class:

use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;

public function buildRules(RulesChecker $rules): RulesChecker {
    $rules->add($rules->isUnique(['email', 'department'], __('The email and department should be unique')));
return $rules;
}

https://book.cakephp.org/4/en/orm/validation.html

Upvotes: 3

Related Questions