0

I remember in Drupal 7, this was possible. I need to add some HTML before a field and I don't want to edit it in the Twig file. Is it somehow possible to add prefixes / suffixes by using the template_preprocess_field function?

I already tried something like that, but with no success:

function MYTHEME_preprocess_field(&$variables, $hook) {
    $element = $variables['element'];
    if ($element['#field_name'] === 'field_genre') {
        $element[0]['#prefix'] = '<div class="project-info">';
    }
    if ($element['#field_name'] === 'field_duration') {
        $element[0]['#suffix'] = '</div>';
    }
}
5
  • 3
    Yep that's still the same. You're just discarding the changes, you want $element = &$variables['element']; – Clive May 4 '18 at 13:57
  • Darn, that was stupid! Thanks! However, even after changing this, it won't work. Do I need to use the Delta Array? Or is prefix and suffix generally for a field rather than a single value inside it? – SoBiT May 4 '18 at 14:00
  • 2
    Yeah you might need to dig further down in the array - look for the child with '#type' => 'textfield' or '#type' => 'select' or whatever, that's the element that needs the prefix/suffix – Clive May 4 '18 at 14:09
  • 2
    Yes, you should be able to add a prefix/suffix to any render element, but not in $variables['element'], because in preprocess the fields are already copied to $variables['items'], see template_preprocess_field(). – 4k4 May 4 '18 at 14:16
  • Thanks! I'm now able to create prefixes and suffixed. However, the prefix is rendered inside the div.field__item - I'd like to render it outside the div.field which is 2 levels above. Is it possible? – SoBiT May 4 '18 at 15:31
0

to prefix a paragraph field, this needs to be put into mytheme.theme .

function mytheme_preprocess_paragraph(&$vars) {
  if (isset($vars['elements']['#paragraph']) && ($vars['elements']['#paragraph']->getType() == 'hp_dean')){
    //kint($vars);
    $vars['content']['field_hp_dean_title']['#prefix'] = '<div class="cont-wrap">';
    $vars['content']['field_hp_dean_more']['#suffix'] = '</div>';
  }
}

you can adjust this to your specific hook, like hook_preprocess_node and similar .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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