I need to make sure that an email field is unique for the current contacts table and I want to make sure that same email is unique to the users table as well. If it is not found in either table then allow the data to be saved.
I am not sure if I am retrieving the data in the best way. This is the only way I have found to work.
Also, I can get the custom check to work and it will return false if the email exists and true if the email doesn't exists, but it still saves the data. Not sure how to tell it not to save the data if the email was found.
Here is my contacts table model currently:
<?php
namespace App\Model\Table;
use App\Model\Entity\Contact;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* Contacts Model
*/
class ContactsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('contacts');
$this->displayField('first_name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->allowEmpty('id', 'create');
$validator
->add('email', [
'validateEmail' => [
'rule' => 'validateEmail',
'provider' => 'table',
'message' => 'That email already exists'
]
])
->requirePresence('email', 'create')
->notEmpty('email');
return $validator;
}
//check that the email is unique in both the Contacts table and in the Users table
public function validateEmail($value, $context) {
$usersTable = TableRegistry::get('Users');
$contactsTable = TableRegistry::get('Contacts');
if ( $contactsTable->exists(['email' => $value]) || $usersTable->exists(['email' => $value]) ) {
return false;
} else {
return true;
}
}
}