I have a custom field formatter (in Drupal 8) that displays a list of taxonomy terms on a node. Some terms are not meant to be displayed, so the field formatter removes them from the items list.
Occasionally, all items are removed -- yet the HTML elements that wrap the field are still rendered. How do I hide the field completely when all items are removed?
EDIT FOR CLARITY:
I have a field with machine name field_tags that is an entity reference to multiple taxonomy terms.
To render this field, I wrote a custom formatter as a field formatter plugin in a custom module. The code is stored in the standard location in mymodule/src/Plugin/Field/FieldFormatter/TermListFormatter.php
My class extends EntityReferenceFormatterBase.
In my class, my viewElements() method strips out some items as needed and sometimes returns an empty array if no items should be rendered.
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Loop through each of the terms in this field.
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
$label = $entity->label();
// ONLY show taxonomy terms that begin with "Test".
if (mb_substr($label, 0, 5) === 'Test') {
$options = [
'query' => [
'tags' => [$entity->id()],
],
];
// Output terms as links to /test?tags[]={tid}
$elements[$delta] = [
'#type' => 'link',
'#title' => $label,
'#url' => Url::fromRoute('view.test.page_1'),
'#options' => $options,
];
if (!empty($items[$delta]->_attributes)) {
$elements[$delta]['#options'] += ['attributes' => []];
$elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
// Unset field item attributes since they have been included in the
// formatter output and shouldn't be rendered in the field template.
unset($items[$delta]->_attributes);
}
$elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
}
}
// This will be an empty array if there were no terms beginning with "Test"
return $elements;
}
When all the terms are stripped out, the field wrapper elements are still output as follows:
<span class="views-field views-field-field-tags">
<span class="field-content"></span>
</span>
How do I stop these elements from appearing when there are no terms to show?
views-field views-field-field-tags
classes). Did you try locating this view and altering it by checking the "NO RESULTS BEHAVIOR/Hide if empty", and/or "STYLE SETTINGS" or "REWRITE RESULTS" to remove the wrappers entirely?