3

Sometimes in theming I want to programmatically hide the prefix or suffix of numeric fields. How can I do so?

1

2 Answers 2

4

When you look at the code of the numeric field formatter:

NumericFormatterBase::viewElements

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $settings = $this->getFieldSettings();

    foreach ($items as $delta => $item) {
      $output = $this->numberFormat($item->value);

      // Account for prefix and suffix.
      if ($this->getSetting('prefix_suffix')) {
        $prefixes = isset($settings['prefix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['prefix'])) : [''];
        $suffixes = isset($settings['suffix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['suffix'])) : [''];
        $prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
        $suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
        $output = $prefix . $output . $suffix;
      }
      // Output the raw value in a content attribute if the text of the HTML
      // element differs from the raw value (for example when a prefix is used).
      if (isset($item->_attributes) && $item->value != $output) {
        $item->_attributes += ['content' => $item->value];
      }

      $elements[$delta] = ['#markup' => $output];
    }

    return $elements;

You see three things, first this is fully configurable, so it has not to happen in the first place, second it's hard to change afterwards, because the field content and the prefix/suffix is concatenated into one string and third you can get the raw values without prefix/suffix from the items attribute content:

field--field-number.html.twig

<h3>Field raw values:</h3>
<ul>
  {% for item in items %}
    <li>{{ item.attributes.content }}</li>
  {% endfor %}
</ul>
1
1

This answer is for Drupal 7 users and does not address the original question.

The following is an example of what someone might add to their theme template.php file. Use Devel to find your field values.

if(some value = true){
    hide($variables['content']['field_name']..['#prefix']);
    hide($variables['content']['field_name']..['#suffix']);
    $variables['field_without_prefix_or_suffix'] =  render($variables['content']['field_name']);        
}

And then just render the variable within your TPL file.

print $field_without_prefix_or_suffix;
2
  • Thank you so much for your help and reply, but my question about Drupal 8. Commented Sep 30, 2017 at 22:57
  • 1
    This is my mistake, off hand, I am unsure of how this is done in D8. Commented Sep 30, 2017 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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