Score:0

Theme a field widget with twig

us flag

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)) {
    return;
  }

  foreach ($terms as $term) {
    $parent = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadParents($term->id());
    $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?

ru flag
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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.