1

Can someone explain or post an example of how to get a third party field settings on every content entity forms?

I'm looking for a generic code where a form can be customized (like calling a custom validator) if any field present in that form is having the third party settings that I have defined.

It could be a node form, a block form, a paragraph etc.

1 Answer 1

2

Implement hook_field_widget_form_alter() to alter form elements of any content entity form.

For example how to add a validate callback when you have third party settings stored in the field configuration:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition instanceof \Drupal\field\FieldConfigInterface) {
    $mymodule_settings = $field_definition->getThirdPartySettings('mymodule');
    if (!empty($mymodule_settings)) {
      $element['#mymodule_settings'] = $mymodule_settings;
      $element['#element_validate'][] = 'mymodule_element_validate';
    }
  }

}
3
  • Thanks @4k4 , is there a way to pass my third party settings values to the #element_validate function?
    – wilNev
    May 26, 2020 at 15:48
  • You can store it in $element. See the edited code.
    – 4uk4
    May 26, 2020 at 16:14
  • Amazing! Thanks for the quick response @4k4. You Rock!
    – wilNev
    May 26, 2020 at 17:05

Your Answer

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

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