0

I'm trying to figure out how Drupal works. I created a simple module named "myModule".

In its myModule.module file I have:

<?php

function myModule_node_view($node, $view_mode, $langcode){
drupal_add_js(array('myModule' => array('nid' => $node->nid)), 'setting');
           }
?>

on myModule.js file I have:

    (function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      jQuery("#test").bind('click', function(e) {
        alert(Drupal.settings.myModule.nid);
      });
    }
  };
}(jQuery));

On my view which has nodes (articles), I created a custom field which has

<a id="test" href="#"Testing!!!</a>

So basically what I want is when I click on the Testing!!! link to show an alert which shows the node id (nid) that belongs to the article in the view's row.

Right now it's showing the nid of the current node I am in, not the view's row.

1 Answer 1

3

in your drupal_add_js, you are setting 1 variable many times. (Drupal.settings.myModule.nid). So the last one will be what this is set to.
You could add these nids to an array in Drupal.settings.myModule but then you would still need a reference from anchor in the views row that maps to the appropriate array index in your Drupal.settings.myModule array.

I think the best / easiest way to get what you want would be to set a data attribute in your views anchor using a token of the current rows nid.
Also, set it up as a class instead of an id, so you don't have the same id multiple times.
eg.

<a class="nid-button" data-nid="[node:nid]" href="#"Testing!!!</a>

Then in your javascript you would just need to use this data attribute.

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      jQuery(".nid-button", context).bind('click', function(e) {
        alert($(this).data('nid'));
      });
    }
  };
}(jQuery));

Doing it this way you don't even need to set any settings variables, instead it is saved on the anchor itself.

Your Answer

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

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