1

Using Drupal 8/9. When trying to view previous revisions I am getting the following error:

Error: Call to a member function getType() on string in clc_d8_theme_theme_suggestions_page_alter() (line 13 of /var/www/html/wrc/web/themes/clc_d8_theme/clc_d8_theme.theme)

It refers to this code:

function clc_d8_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType()); <-- error at this line
  }
}

I need the type suggestions for my theme. How do I fix this? I thought the check on the node would be enough to avoid issues.

1 Answer 1

3

"$node" can vary a bit by context, but here are some ways to set $node:

$routeName = \Drupal::routeMatch()->getRouteName();

$node = NULL;

// $variables['node'].
if (isset($variables['node'])) {
  $node = $variables['node'];
  if (is_numeric($variables['node'])) {
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['node']);
  }
}

// $variables['row'].
if (isset($variables['row']) && !empty($variables['row']->nid)) {
  $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['row']->nid);
}

// $routeName === 'entity.node.canonical'.
if ($routeName === 'entity.node.canonical') {
  $node = \Drupal::routeMatch()->getParameter('node');
}

// $routeName === 'entity.node.revision'.
if ($routeName === 'entity.node.revision') {
  $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId();
  $node = node_revision_load($revisionId);
}

// $routeName === 'entity.node.preview'.
if ($routeName === 'entity.node.preview') {
  $node = \Drupal::routeMatch()->getParameter('node_preview');
}

if ($node) {
  // run your code...
}

Specifically, it looks like you're after:

// Get route name.
$routeName = \Drupal::routeMatch()->getRouteName();

// Check if route is node revision.
if ($routeName === 'entity.node.revision') {
  $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId();
  $node = node_revision_load($revisionId);
}

This will fully load your node object and ->getType() should work without error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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