Senchu Thomas
Senchu Thomas

Reputation: 568

Validate field as unique with scope in cakephp

I am creating a CakePHP application which have an edit form which contain one text box named air_id. In my table I am using project_id and air_id as composite primary key. So while updating air_id I need to validate uniqueness. My table structure is like:

   project_id         air_id       
       1            [email protected]  
       1            [email protected]

Currently I am using cakephp3.0 and I am using validateUnique rule with scope, Following is my code:

 $validator
        ->add('air_id', [
            'unique' => [
                'rule' => ['validateUnique', ['scope' => 'project_id']],
                'provider' => 'table',
            ]
]);

And my controller is like this

$projectCustomers = $this->ProjectCustomers->newEntity($formData);

Now it is giving validation message every time. What I need is when I change the value [email protected] to [email protected] it should raise the error and if I change it to some other value it should not raise the error. Is there something wrong in my validation?

Upvotes: 0

Views: 837

Answers (1)

Manohar Khadka
Manohar Khadka

Reputation: 2195

CakePHP Unique Field Rules:

We have cakephp unique field rules that might be even better:

In your table(eg. UsersTable.php):

 public function buildRules(RulesChecker $rules)
 {
    $rules->add($rules->isUnique(
       ['air_id', 'project_id'],
       'Your validation error here.'
    ));

    return $rules;
 }

At the top of your table , don't forget to include this class:

use Cake\ORM\RulesChecker;

See Here (CakePHP Unique Fields Rules).

Upvotes: 2

Related Questions