0

While showing a node, only the filled fields are rendered. I wanted to be able to show the empty field labels, and I was looking for something like the ability to uncheck an option such as 'Hide if empty' or check a 'Display even if empty.'. Unfortunately, there are no such options. In order to display them, I used a hook_preprocess_node:

/**
 * Implements hook_preprocess_node().
 */
function MYMODULE_preprocess_node(&$variables) {
    $node = $variables['node'];
    $all_fields = $node->getFieldDefinitions();
    $node_fields = $node->getFields();
    foreach ($node_fields as $field_name => $field) {
        $value = $field->getString();
        if (str_contains($field_name, 'field_') && !$value) {
            $variables['content']['_field_layout']['content'][$field_name] =
            [
                '#theme' => 'field',
                '#title' => $label = $all_fields[$field_name]->getLabel(),
                '#field_type' => $all_fields[$field_name]->getType(),
                '#label_display' => "inline",
            ];
        }
    }
}

This made all the hidden fields display, but are not honouring the order set on the node display. Is there a way to get and pass a #weight?

2
  • I think you could render those through the managed display section from content types. Jan 23, 2023 at 0:38
  • Thank you @harsh-vashisht, but that's not an option using core. It made me however look for contrib again and I did find what I was looking for. Jan 23, 2023 at 9:30

2 Answers 2

2

I found a contrib module that allows showing hidden fields: https://www.drupal.org/project/empty_fields

Thank you for people chipping in that made me dig deeper ( I still can't believe how I missed it before moving to the preprocess 😔 )

0

As far as understand, most (if not all) twig files check:

if the field is empty
    don’t show both label or content
else
    show everything

I’ve came across the kind of situation you describe. My solution was to change (appropriately) the twig files so that the label is outside the if statement.

3
  • Yes, that was my initial thought, however {{ content }} in the node.html.twig template is already missing the info such as labels from empty fields. Jan 22, 2023 at 19:21
  • No. I'm referring to field.html.twig or some other template at the field level. Jan 22, 2023 at 21:13
  • Unfortunately, those templates are only being called for fields with content. I think something in core is removing it from the rendered array. The preprocess above was an attempt to add it again...and it does, but not in the correct order. Jan 23, 2023 at 9:24

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.