Getting node IDs in theme preprocess functions in Drupal 8

October 09, 2015

From a front-end point of view, most of the noise being made about changes from Drupal 7 to 8 have been around Twig and the libraries API. From my (limited) experience with Drupal 8 so far, both of these seem to be very positive changes.

The big change in Drupal 8 generally, though, is the move to object-oriented programming. If you think of yourself as a themer (and for some reason that’s a word I dislike), you might think that this is something that only back-end developers need to worry about. However, it does have an impact on the code that you’ll write in your .theme file (template.php in old money).

For instance, because the properties of the node object are protected, you can’t access them directly the way you may have done in Drupal 7 code. So if you want to use them in preprocess functions, you’ll need to use the relevant getter functions to access them. Here are some examples where you’ll need to change the way you access properties:

Drupal 7 template_preprocess_node

function mytheme_preprocess_node(&$vars) {
  // Get the node ID.
  $nid = $vars['node']->nid;

  // Get the author ID.
  $uid = $vars['node']->uid;
}

Drupal 8 template_preprocess_node

function mytheme_preprocess_node(&$vars) {
  // Get the node ID.
  $nid = $vars['node']->id();

  // Get the author ID.
  $uid = $vars['node']->getOwnerId();
}

From other places in the preprocess flow, you’ll need to do a little bit more if you want to get at the node object though, for instance:

Drupal 7 template_preprocess_html

function mytheme_preprocess_html(&$vars) {
  $menu_object = menu_get_object();
  if (is_object($menu_object) && property_exists($menu_object, 'nid')) {
    $nid = $menu_object->nid;
  }
}

Drupal 8 template_preprocess_html

function mytheme_preprocess_html(&$vars) {
  $node = \Drupal::request()->attributes->get('node');
  $nid = $node->id();
}