2

I'm trying to make a theme suggestion for form-element--first-name--23.html.twig using the following function, based on some information from Drupal 8 / 9 – Adding theme suggestions for node id specific field template.

EDIT: Not sure what needs to be clarified, per admin. But to reiterate, I can't figure out how to make a theme suggestion using a field ID and node ID in the same suggestion. The code provided below is what I came up with. There is nothing to compare it against. I'm trying to adjust the code to do what I need. If this isn't the forum for questions, I can take this somewhere else.

EDIT 2: For further clarity, there is nothing to compare it against because the provided code DOESN'T WORK. So I'm seeking assistance getting the code to work.

function mytheme_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  $object = $variables['element']['#object'];
  $id = str_replace("-", "_", $variables['element']['#id']);
  if (get_class($object) == 'Drupal\node\Entity\Node') {
    $suggestions[] = $hook . '__' . $id . '__' . $node->id();
  }
}
4
  • 1
    I wouldn't try to style form elements this way. It's much each easier to use hook_form_alter() and inject #theme or #theme_wrapper entries to achieve the styling required. Feb 12 at 17:52
  • The question doesn't make clear what problem you get when you try to achieve what the question describes. Does the code work as expected? If it doesn't, what is the difference between the expected result and what you obtain?
    – apaderno
    Feb 13 at 16:58
  • I guess I'm confused. There's not a "problem." I'm trying to solve something I can't seem to find a solution for. It's exactly as stated in the question, how do I make a theme suggestion that uses the field ID and node ID. I provided the code I created to try to solve the problem. That code doesn't work. I'm not sure what you need clarified. Please reopen question.
    – cofihouse
    Feb 13 at 22:58
  • I ran into this issue as well working with Drupal 9. This solution worked for me. I had to manually define a template for the form_element. Note, defining the theme file in "hook_theme()" makes it necessary to place the twig file in the top level of the "templates" folder for your theme to work (so no automatic recognition if placed in sub-folders).
    – Jason
    Nov 21 at 16:38

0

Browse other questions tagged or ask your own question.