Incorporating Drupal.settings into your module code.

Justin Langley
|
August 8, 2015
Image
Code screenshot

The javascript Drupal object has been designed to do awesome things. So let's see how to do awesome things with it!

What is Drupal.settings?

An example here would be: Drupal.settings.myModule.basePath

Where Drupal is the Drupal object that is declared in the very first line of the base drupal.js file. It has 4 objects inside of it: settings beahviors themes and locale. This settings object contains PHP code that has been passed to it. The best way to explain this is with an example.

Say you want to pass on the base path of your Drupal installing from your module code. Your module code would then look like this:

function pass_base_path() {
    global $base_url; // This is the global variable Drupal has set which contains the root URL of the Drupal installation
    $pathURL = array(
        'basePath' => $base_url,
     );
     $myModule = array(
        'myModule' => $pathURL,
     );
    drupal_add_js($myModule, 'setting');
}

The way Drupal handles the passing of PHP to the Javascript Drupal object is by passing an array of "namespace" each of which contain an array of settings keyed by whatever you want to call it. First your value needs to be in a keyed array:

$pathURL = array(
    'basePath' => $base_url,
);

So your $base_url value is accessible by the key name basePath. Next you need to "namespace" your array. (This is so you don't have to worry about another module using the same key name)

$myModule = array(
    'myModule' => $pathURL,
);

And this will make your basePath key live under the myModule namespace inside the Drupal.settings object! How neat is that?


Why is this useful?

Just as a real-case example, in our Sociy project we use Ckeditor and the IMCE bridge for setting up WYSIWYG editors for users. We built the CSS in a way that changing a body class will then change the primary and secondary colors of the theme. Which worked wonderfully; until we needed to have these colors also show up in our WYSIWYG editor when a user was trying to make, say a header using the primary color.

So now we needed a way to tell the Javascript to add this body class to the WYSIWYG editor's iframe. So the module that handles the switching of the body classes now also passes that body class to the Drupal.settings object, which we can then use to apply the body class to the editor. Here is the snippet:

$settings = array(
    'theme_class' => $themeClass,
);
$passThisToTheScripts = array(
    'sociy_theme_switcher' => $settings,
);
drupal_add_js($passThisToTheScripts, 'setting');

And that's it! That's all it takes. Using this bridge between the module's PHP Code and the Javascript is an awesome way to apply front end configuration based on backend configuration. If you want to read up on the Drupal Javascript API you can check it out here

Want to talk about how we can work together?

Ryan can help

Ryan Wyse
CEO