0

Using Drupal 9,

How do I hide a node field when viewing it?

Let's say I have field info. I would like to conditionally not display the label or the value.

I assume I use hook_node_view_alter but I'm not familiar with how to manipulate the build render array.

Thanks!

2
1

You could make use of the hook_preprocess. If its on the specific entity such as the case of a paragraph it will look something like this where I am hiding some labels from a view based on some condition:

function [MODULE_NAME]_preprocess_paragraph(&$variables){
    $paragraph = $variables['paragraph'];
    // Get the parent bundle.
    $parentBundle = $paragraph->getParentEntity()->bundle();
    //check View type
    if ($parentBundle && $parentBundle == 'category_views') {
      if ($variables['content']['field_language_name']['#object']->get('field_language_name')->value != 'English') {
       //Removing labels
        unset($variables['content']['field_language_name']);
        unset($variables['content']['field_language']);
      }
    }
}
2
  • So the key here is to use this in a hook_preprocess function: unset($variables['content']['field_language_name']); unset($variables['content']['field_language']); – dca123 Sep 10 '20 at 14:04
  • 1
    I used hook_preprocess_node and unset($variables['content']['field_info']) to hide it. – dca123 Sep 10 '20 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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