As I'm building form elements dynamically I want to be able to check and see if a form field is required or not via a custom validation rule. The problem is that when I add a custom validation rule, it forces the field to not be empty. If I allow the field to be empty, it doesn't check my custom validator unless something is entered in the field.
How can I check in a callback whether to allow or not a field as required?
In my SubmissionsTable
public function validationDefault(Validator $validator)
{
$validator
->add("custom_value_q", [
"custom" => [
"rule" => [$this, "customFieldIsRequired"],
"message" => "Message Here"
]
]
);
return $validator;
}
public function customFieldIsRequired($value, $context)
{
//logic here
return true;
}
Returning true in your custom one when empty $value is passed in should do the trick.
If you want the field to allow empty string (= empty), use allowBlank('custom_value_q') on top, logically you don't need to invoke the custom validator function then, that's why it is bypassed in the empty case.
//UPDATE You do, however, have the option to provide a callback for allowEmpty(), with this it should be possible to only invoke the custom validation rule if you really want it (if the field needs to be validated because non blank).
$validator->allowEmpty('fieldname', function ($context) { return !isset($context['data']['description']) || $context['data']['description'] !== ''; });