2

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

NoobieErrors
  • 31
  • 1
  • 2
  • So how _do_ you validate the uniqueness of a single field? Via the `validateUnique` rule? – ndm Dec 14 '20 at 10:59
  • Well i'm new to cakePHP and i'm having trouble to wrap my head around validators and rules which kind of mix in together but yes via the validateUnique rule. – NoobieErrors Dec 14 '20 at 13:48
  • I have edited the post so you can see what I have atm – NoobieErrors Dec 14 '20 at 13:59
  • The validator still works as documented. The domain rules are just a different (and often not correct) way of doing things. So just use the documented way also in 3.x and 4.x and it will work all as expected. – mark Dec 14 '20 at 15:42

1 Answers1

2

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