Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this post, I'll show you how do I get the current node ID in drupal 8.

<?php

/**
 * @param $variables
 */
function mymodule_preprocess_page(&$variables) {

  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'entity.node.canonical') {

    /**
     * method 1
     */
    $entity = \Drupal::routeMatch()->getParameter('node');
    if ($entity instanceof \Drupal\node\NodeInterface) {
      $nid = $entity->id();
    }

    /**
     * method 2
     */
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->id();

  } elseif ($route_name == 'entity.node.preview') {

    /**
     * Example for node preview page
     */
    $node = \Drupal::routeMatch()->getParameter('node_preview');
    $nid = $node->id();

  }
}

Tags :

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook