1

I previously asked a question about hiding the prefix/suffix in fields template here, now I want to understand how can I programmatically hide the prefix or suffix of numeric fields in nodes templates only?

1
  • You cannot. The field template that renders those values has no access to context in which it is being rendered(ie. access parent(s)). The only solution is to use hook_form_alter in your theme and alter specific fields in specific form.
    – user21641
    Oct 1, 2017 at 17:18

2 Answers 2

1

On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.

So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.

A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:

{{ node.field_example.value }}

But then you lose all formatting options, not only prefix/suffix.

0
1

You could remove the prefix via

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_view_alter/8.2.x.

In case you need it for comments.

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_comment_view_alter(array &$build, CommentInterface $comment, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($comment->getFieldName() === 'field_name') {
    unset($build['#prefix']);
  }
}

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.