Score:1

Error when trying to view revisions

do flag

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.

Score:3
ve flag

"$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');
  $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');
  $node = node_revision_load($revisionId);
}

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

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.