Sometimes in theming I want to programmatically hide the prefix or suffix of numeric fields. How can I do so?
2 Answers
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>
-
Thanks, I asked a new question here: How to show/hide the prefix/suffix of fields in node templates?. Commented Oct 1, 2017 at 16:27
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;
-
Thank you so much for your help and reply, but my question about Drupal 8. Commented Sep 30, 2017 at 22:57
-
1This is my mistake, off hand, I am unsure of how this is done in D8. Commented Sep 30, 2017 at 23:06