Reputation: 14544
I am trying to add an application rule which prevents duplicate rows being saved.
I followed the book about creating unique field rules but it doesn't seem to work, or I'm doing something wrong.
<?php
namespace App\Model\Table;
use Cake\ORM\Rule\IsUnique;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
class CustomersTable extends Table
public function buildRules(RulesChecker $rules)
{
return $rules->add($rules->isUnique(['email']));
}
}
Just performing a straight save:
$this->loadModel('Customers');
$this->Customers->save($customer);
Having looked at the IsUnique class source code, I get that it should be getting called via its __invoke()
magic method but my application is still throwing an exception due to the duplicate row trying to save.
Is there anything incorrect with my code above?
Upvotes: 1
Views: 1849
Reputation: 9717
May be you just forget to add the validation class and entity
It may look like this
namespace App\Model\Table;
use App\Model\Entity\Customer;//
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class CustomersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');//
//$this->table('customers'); *u can also specify ur table like this
}
public function validationDefault(Validator $validator)
{
$validator
->notEmpty('email')
->requirePresence('email')
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(array('email')));
return $rules;
}
}
Upvotes: 1
Reputation: 53
You should create your own custom validator for this. Also you should check if it matches the current user id for example if you want to let it work on updates.
public function validationDefault(Validator $validator)
{
$validator->add('email', 'uniqueEmail', [
'rule' => function ($value, $context) {
if(isset($context['data']['id'])) {
return !$this->exists(['email' => $value, 'id !=' => $context['data']['id']]);
}
return !$this->exists(['email' => $value]);
},
'message' => 'Email address already registered',
]);
return $validator;
}
Upvotes: 0