0

I have code that adds #element_validate to all fields of a certain type (Link fields).

$form[$field_name]['widget'][0]['#element_validate'][] = '_fix_link_field_value';
array_unshift($form[$field_name]['widget'][0]['uri']['#element_validate'][0], '_fix_link_field_value');

This works fine, but I get this warning in the logs every time an entity with this field type is saved.

Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in Drupal\Core\Form\FormValidator->doValidateForm() (line 282 of E:\www\Noah\pre\web\core\lib\Drupal\Core\Form\FormValidator.php).

I suspect this is because the existing validator has the format [class, method]. Is there any way to mix these validator formats?

1 Answer 1

3

#element_validate expects an array of validation callbacks.

A callback can either be the function name of a globally accessible function, or an array of a class name and method name.

Now I am supposing that '_fix_link_field_value' is the name of a globally available function defined in your module.

So for using it as a validation callback, there is no array required here.

While the first line of your code is adding this callback to the callbacks of #element_validate, the second line is prepending it to an existing callback array, resulting in the following '#element_validate' value:

[[
  '_fix_link_field_value',
  (class),
  (method),
]]

Which won't work. You'd need:

[
  '_fix_link_field_value',
  [
    (class),
    (method),
  ]
]

So what you really want to do is to remove the trailing [0] from your array_unshift call:

if (!empty($form[$field_name]['widget'][0]['uri']['#element_validate']) && is_array($form[$field_name]['widget'][0]['uri']['#element_validate'])) {
  array_unshift($form[$field_name]['widget'][0]['uri']['#element_validate'], '_fix_link_field_value');
}
else {
  $form[$field_name]['widget'][0]['uri']['#element_validate'] = [
    '_fix_link_field_value',
  ];
}
2
  • Thanks and yes, that makes sense and pretty I tried that. Will try it again.
    – liquidcms
    Nov 11, 2022 at 4:09
  • 1
    Yes, that was it, and i also did try that already. My problem was my validator function was not correct; but oddly enough when (as shown above) i was also adding the validator to the widget (incorrect) as well as the uri part of the widget (correct) the 2 mistakes seemed to give the desired result - but with the warning which I had not seen until now. Thanks again for having me take another look at it.
    – liquidcms
    Nov 11, 2022 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.