I am using CakePHP 3.5.5.
I am struck with a custom validation rule. I have country and state fields in my view. In case if the value of country field is US then we make state field required otherwise we don't. I have put a custom validation rule in my UsersTable.php like this:
public function validationDefault(Validator $validator) {
$validator
->add('state', 'custom', [
'rule' => [$this,'validate_state'],
'provider' => 'custom',
'message' => 'Please enter state'
]);
}
and have created validate_state function like this:
public function validate_state($value, $context) {
//debug($value, $context);die;
//if state is us)
//if state is not empty return true;
//if state is empty return false;
//else return true;
}
But it not working at all. The only thing it is doing is showing the "This field cannot be left empty" message if I use this rule. I understand that CakePHP assumes to run notEmpty on its own if you have created a validator rule for a field. But my problem is I cannot rule field value true or false before checking the value of another field for which I need to use custom function before checking the notEmpty method. But in my case here if I dont use notEmpty method it neither is entering the custom function validate_state nor it is showing the custom message i use in this rule.
Do you know a better way to do it without hacking the form request data before sending it to validator?