I want to add a class to the page tile block of specific node types so as to conditionally show and hide it. I arrive at this (page preprocessor already exist, added ‘add class to page_title block to hide & show’ to achieve the show/hide):
use DrupalComponentUtilityHtml; use DrupalCoreTemplateAttribute; use DrupalnodeNodeInterface; use DrupalnodeEntityNode; /** * Implements template_preprocess_page(). */ function bd_classy_preprocess_page(&$variables) { if (isset($variables['node'])) { $node = $variables['node']; // Adds additional classes. if ($node && is_int($node)) { $node = Node::load($node); } if ($node instanceof NodeInterface) { $path = 'path' . Html::cleanCssIdentifier($node->toUrl()->toString()); $variables['attributes']['class'][] = $node->getType(); $variables['attributes']['class'][] = $path; //add class to page_title block to hide & show if ( $node->hasField('field_hide_title') && ($node->getType() == 'cage' || $node->getType() == 'over_land') ) { $block = DrupalblockEntityBlock::load($variables['elements']['#id']); if ($block == 'bd_classy_page_title' && $node->get('field_hide_title')->value == 1) { $variables['attributes']['class'][] = 'visually-hidden'; } else { $variables['attributes']['class'][] = 'visible'; } } else { $variables['attributes']['class'][] = 'visually-hidden'; } // end adding class } } }
It’s not working and I’ve got these errors in log:
Checked log messages and found these:
- Notice: Undefined index: elements in bb_classy_preprocess_page() (line 38 of /var/www/html/web/themes/custom/bd_classy/bd_classy.theme) - Notice: Trying to access array offset on value of type null in bd_classy_preprocess_page() (line 38 of /var/www/html/web/themes/custom/bd_classy/bd_classy.theme) - Warning: assert(): Cannot load the "block" entity with NULL ID. failed in DrupalCoreEntityEntityStorageBase->load() (line 295 of /var/www/html/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php) - Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalCoreEntityEntityStorageBase->loadMultiple() (line 312 of /var/www/html/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php)