Implementing hook_field_widget_single_element_WIDGET_TYPE_form_alter is altering the widget. It makes sense to theme the changes in a twig template. Here's the widget form alter code:

 * Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
function my_module_field_widget_single_element_entity_browser_entity_reference_form_alter(array &$element, FormStateInterface $form_state, array $context) {
  $field_name = $context['items']->getName();
  $terms = $element['entity_browser']['#default_value'];
  if (!isset($field_name) || !isset($terms)) {

  foreach ($terms as $term) {
    $parent = \Drupal::entityTypeManager()
    $parent = reset($parent);
    $term->setName(trim($term->getName()) . ' | ' . trim($parent->getName()));

How do I do pass values like $parent->getName() to a twig template in a custom module?

  • Field widgets need to work independently of a theme/template, therefore widgets very often use Form API and not dedicated Twig templates. $element is a render element (render array) and therefore accessible in Twig, but there usually will not be a Twig file for this.
    – Hudri
    Apr 4 at 6:49


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.

Browse other questions tagged or ask your own question.