In your MODULENAME.module file:

$testVariable = 'himanshu';
drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');

In MODULENAME.js file:

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

this way you can pass your php variable in drupal javascript file and use the variable :)

How can I implement the above in Drupal 8?


Instead of drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting')); you use $build['#attached']['drupalSettings']['testvar'] = $testVariable;. Replace $build with the variable containing the form or the render array to which the settings are attached; in a form builder or hook_form_alter(), that would be $form.

The JavaScript code to attach to the page should then be defined as library, which is the only way to attach JavaScript and CSS to a page or a form.
It is explained in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module, so I will not repeat it here. I will just make notice that the library needs to declare at least two dependencies:

  • core/jquery, if the JavaScript code uses jQuery
  • core/drupalSettings, since the JavaScript code uses Drupal settings

For Drupal 8 you can do.

 * Implements hook_page_attachments().
function mymodule_page_attachments(array &$page) {
  $page['#attached']['drupalSettings']['myname'] = 'himanshu';

(function ($, Drupal, drupalSettings) {
   * @namespace
  Drupal.behaviors.mymoduleAccessData = {
    attach: function (context) {
      var data = drupalSettings.myname;
})(jQuery, Drupal, drupalSettings);

Another way to do it (as mentiond in JS-standards) would be:

$element['#attached']['js'][] = array(
  'data' => array('myModule' => array('basePath' => base_path())), 
  'type' => 'setting',

This variable would then be referenced from JS side like:

  • This code is not valid for Drupal 8. – arnoldbird Mar 13 '20 at 22:32
  • 1
    Indeed, it's invalid. Instead, do : $build['#attached']['drupalSettings']['myvar'] = 'allo'; – JFK Mar 17 '20 at 2:23

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.