8

Is there a definitive, universal way to do this? For example using some environment variable that comes with Drupal.behaviours?

I have done some research and there seems to be no common answer.

  • No there's no environment variable like that...what exactly do you mean by 'get the drupal node id'? What are you classing as 'the drupal node id' in this context? The ID of a node whose full page you're on? – Clive Jul 8 '13 at 12:26
  • yes, the ID of a node whose full page I'm on, e.g. as in mysite.com/node/6 I would like the jquery I execute from this page to be able to obtain the node id and put it into a variable, in the example, this would have the value of 6. – therobyouknow Jul 8 '13 at 12:29
  • If you want a robust method you'll have to pass the node ID from the server side manually using drupal_add_js(); the nid isn't ever used on the client-side by core so there's no need for it to be added as a setting usually – Clive Jul 8 '13 at 12:32
13

As mentioned above, Drupal core has no use for the node ID on the client side so it doesn't pass it through. if you want access to it you'll need to add it manually:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full') {
    $setting = array('MYMODULE' => array('currentNid' => $node->nid));
    $node->content['#attached']['js'][] = array(
      'data' => $setting,
      'type' => 'setting',
    );
  }
} 

Then on the client side you'll have access to it through Drupal.settings:

var currentNid = Drupal.settings.MYMODULE.currentNid;
| improve this answer | |
  • Thanks @Clive - very happy with this solution! I will try it out. It will help me with my attempt to fix pop_links module issue: Version 7 Not Recording Links. I will credit you with the help, feel free to chip in too. My findings so far with this module are that the javascript they provide is not "firing" and a colleague has provided an interim fix based on a class attribute from the bootstrap theme. Ultimately we are aiming towards a theme independent solution. – therobyouknow Jul 8 '13 at 12:40
  • May I mention a working correction to your code: it should read: $setting = array('MYMODULE' => array('currentNid' => $node->nid)); the = is extraneous. That did the job - tacked your code onto this function that already existed in pop_links and added your javascript in pop_links.js. – therobyouknow Jul 8 '13 at 13:27
  • Oops, typo - sorry about that :) – Clive Jul 8 '13 at 13:41
  • 1
    +1 by the way for your answer. It works and has enabled me to provide an interim fix for pop_links issue here: drupal.org/node/1269290#comment-7625019 – therobyouknow Jul 8 '13 at 13:48
  • 1
    P.S. credited you on the solution. – therobyouknow Jul 8 '13 at 14:14
5

As mentioned by MPD in his answer, working with the default css-classes Drupal generates for the element is a easy solution which works without custom PHP code.

Here is our implementation:

(function($) {

  /**
   * Find Drupal Node ID based on <body> element classes.
   *
   * @return Node ID or false
   **/
  function getCurrentNodeId() {
    var $body = $('body.page-node');
    if ( ! $body.length )
      return false;
    var bodyClasses = $body.attr('class').split(/\s+/);
    for ( i in bodyClasses ) {
      var c = bodyClasses[i];
      if ( c.length > 10 && c.substring(0, 10) === "page-node-" )
        return parseInt(c.substring(10), 10);
    }
    return false;
  }


  /**
   * Example usage...
   *
   **/
  Drupal.behaviors.yourModuleNameHere = {
    var nodeId = getCurrentNodeId();
    if ( nodeId ) {
      // Node ID found.
      // ...do something with it.
    } else {
      // Node ID not found. Guess we are not on a node page
      // ...handle this case with care too. 
    }
  }

}(jQuery);
| improve this answer | |
  • this also works on Drupal 8 if you change a line to var $body = $('body.path-node'); (tested with zurb_foundation for 8.x-6.x) – HongPong Sep 20 '18 at 21:09
3

The default template_preprocess_html() has this bit of code in in

if ($suggestions = theme_get_suggestions(arg(), 'page', '-')) {
  foreach ($suggestions as $suggestion) {
    if ($suggestion != 'page-front') {
      // Add current suggestion to page classes to make it possible to theme
      // the page depending on the current page type (e.g. node, admin, user,
      // etc.) as well as more specific data like node-12 or node-edit.
      $variables['classes_array'][] = drupal_html_class($suggestion);
    }
  }
}

This will stick on classes to the <body> element line page-node-123. If you don't want to use your own code in a custom module, you can get the classes via jQuery, find the one that matches page-node-, and then parse out the nid.

| improve this answer | |
  • +1 Thanks for your input @MPD worth knowing. In my case adding stuff to a module suits me as I am fixing a bug in pop_links module - see my comment below Clive's answer. Your answer will, no doubt, be useful in other scenarios. – therobyouknow Jul 8 '13 at 13:28
1

What has worked for me is adding the following line to my page.tpl.php template. This adds the node ID to window.Drupal.settings.nid which you can use at will in JavaScript.

drupal_add_js(array('nid' => $node->nid), 'setting');

As suggested in the comments, here's the code for adding the node ID from template.php:

function MYTHEME_preprocess_page(&$variables, $hook) {

  if ($node = menu_get_object()) {

    drupal_add_js(array('nid' => $node->nid),'setting'); 
  } 
}
| improve this answer | |
  • Maybe better add that line in template_preprocess_page instead (if you need it on the page level). To not mix things up and keep the templates as clean and readable as possible. Templates should be used for markup. – leymannx Nov 28 '18 at 21:08
  • I've done that as well on other builds. Adding it to page.tpl.php is a fairly easy "hack" for folks who are intimidated by the theme. Good suggestion, thank you :) – Daniel Lefebvre Nov 28 '18 at 21:11
  • Is that a typo there settings and setting? – leymannx Nov 28 '18 at 21:14
  • it's not... it threw me a few times... but "setting" goes in the drupal_add_js and it creates window.Drupal.settings.whatever – Daniel Lefebvre Nov 28 '18 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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