next I have provide conditional rules and both compare,
Model\Table\UsersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function buildRules(RulesChecker $rules)
{
$rules->add(function ($entity, $options) use($rules) {
if ($entity->Role == 'Administrator') {
$rule = $rules->existsIn('User', 'Administrator');
return $rule($entity, $options);
}
return false;
}, 'Administrator tidak boleh lebih dari 1');
return $rules;
}
}
the conditional rules inside (UsersTable) that I want output is compare field values Role == Administrator, not greater than one.
the error messages shown is
ExistsIn rule for 'User' is invalid. 'Administrator' is not associated with 'App\Model\Table\UsersTable'.
----------------------------------------------------------------------------------------------------------------
| Nama | Role | Dibuat | Diubah | Aksi |
----------------------------------------------------------------------------------------------------------------
| Budi | Administrator | 04-04-2019 14:33:29 | | Tampil Perbarui Hapus |
---------------------------------------------------------------------------------------------------------------
the rule validation inside UsersTable.php, that’s I want, is prevent add new user with Role = Administrator, more than one,…simply is Role = Administrator just only one users.
existsIn is to make sure that a value exists in another table. For example, if you’re adding a post with a user id, to confirm that the user id is for a real user. Seems that you’re not looking to cross-reference another table here, so existsIn is not at all the right thing. Sounds like you want something more like: