Passing data from PHP to JavaScript in Drupal

Components

This code demonstrates how to make data from a Drupal module available to JavaScript. This technique is often used when there's a need to interact with or manipulate the DOM using values or configurations from the backend.

Initially, we implement the hook_page_attachments() hook to attach data and assets to the page. Here, a cookie_name is retrieved and subsequently passed to JavaScript via the drupalSettings mechanism.

/**
 * Implements hook_page_attachments().
 */
function MY_MODULE_page_attachments(array &$attachments) {
  $cookie_name = some_func();
  $attachments['#attached']['drupalSettings']['MY_MODULE']['cookieName'] = $cookie_name;
  $attachments['#attached']['library'][] = 'MY_MODULE/MY_MODULE';
}

A library, MY_LIBRARY_NAME (found in the MY_MODULE.libraries.yml file), is defined, which references a JavaScript file (js/MY_MODULE.js) and lists its dependencies. This ensures that the script, along with the required core functionalities, gets loaded as needed.

MY_LIBRARY_NAME:
  js:
    js/MY_MODULE.js: {}
  dependencies:
    - core/drupal
    - core/once
    - core/drupalSettings

In the JavaScript portion (found in the js/MY_MODULE.js file), the data passed from PHP is accessed through the drupalSettings object within a Drupal behavior.

(function (Drupal, once, drupalSettings) {

  'use strict';

  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      const elements = once('myModuleBehavior', 'html', context);
      
      elements.forEach(function () {
        let cookieName = drupalSettings.MY_MODULE.cookieName;
        ...
        // do something with cookieName
      });
    }
  };

})(Drupal, once, drupalSettings);

With this setup, any time Drupal renders the page, the cookieName from the PHP backend is made accessible in the JavaScript front end, providing seamless integration between the two.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.