I need to do a conditional validation on a field: if other_field = 1
then this_field = notBlank
. I can not find a way to do this.
My validator in table class:
public function validationDefault(Validator $validator) {
$validator->allowEmpty('inst_name');
$validator->add('inst_name', [
'notEmpty' => [
'rule' => 'checkInstName',
'provider' => 'table',
'message' => 'Please entar a name.'
],
'maxLength' => [
'rule' => ['maxLength', 120],
'message' => 'Name must not exceed 120 character length.'
]
]);
return $validator;
}
public function checkInstName($value, array $context) {
if ($context['data']['named_inst'] == 1) {
if ($value !== '' && $value !== null) {
return true;
} else {
return false;
}
} else {
return true;
}
}
Trouble here is, if i note, in the start of the method, that the field is allowed to be empty, when the entered value is empty, Cake doesn't run through any of my validations, because it's empty and allowed to be such. If i do not note that the field can be empty, Cake just runs "notEmpty" validation before my custom validation and outputs "This field cannot be left empty" at all time when it's empty.
How do i make Cake go through my conditional "notEmpty" validation?
I did try validation rule with 'on' condition with the same results.
Successfully tested, this might help you and others. CakePHP 3.*
$validator->notEmpty('event_date', 'Please enter event date', function ($context) {
if (!empty($context['data']['position'])) {
return $context['data']['position'] == 1; // <-- this means event date cannot be empty if position value is 1
}
});
In this example Event Date
cannot be empty if position = 1
. You must put this condition if (!empty($context['data']['position']))
because the $context['data']['position']
value only will exist after the user click submit button. Otherwise you will get notice error
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With