How to programatically hide node field on viewing?
题
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!
解决方案
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']);
}
}
}
不隶属于 drupal.stackexchange