Drupal 8 – add javascript library with dynamic parameters

Dang… sometimes Drupal really makes you suffer…
But I love it anyhow… poor Drupal, nobody likes it because nobody understands it, LOL.

Ok, let’s get serious, if you have troubles modifying the parameters of an attached Javascript library, you’re not alone, let’s see how to do it.

First, I’m referring to adding javascript as per official documentation:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

Second, the thing I found hard to do was to modify the parameters dynamically, in my case was by using my module’s settings.
So, in other words having something like this:

<script src="https://www.paypal.com/sdk/js?client-id=your_id&vault=true&currency=USD"></script>

Where your_id is the value you want to change dynamically.

In order to achieve that you need to:

Create the yourmodule.module file

The usual, you need a custom module, with the .module file, as per official documentation:

https://www.drupal.org/docs/8/creating-custom-modules/basic-structure

You have to implement the:

/**
 * Implements hook_js_alter().
 */

And, here comes the interesting part:

<?php

use Drupal\Core\Asset\AttachedAssetsInterface;

/**
 * @file
 * The module file.
 */

/**
 * Implements hook_js_alter().
 */
function yourmodule_js_alter(&$javascript, AttachedAssetsInterface $assets) {
    // here you can call this to get your custom settings
    $config = \Drupal::config('MY.settings');
    if(!empty($config->get('client_id')) && !empty($config->get('secret'))) {
        $client_id = $config->get('client_id');
    // Here you replace the default URL with the one you want (included the parameters you need, in my case the client it
        $javascript['https://www.paypal.com/sdk/js?client-id=CLIENT_ID&vault=true&currency=USD']['data'] = "https://www.paypal.com/sdk/js?client-id=$client_id&vault=true&currency=USD";
    }
    _webform_asset_alter($javascript, 'javascript');
}

In this last code block you can see that we completely override the URL of the javascript library even if we just want to add/modify the parameters.

To be noted that you also have to include the following include:

use Drupal\Core\Asset\AttachedAssetsInterface;

In my case I had to call also the _webform_asset_alter function, but my guess is that it’s only needed in my specific case as I’m integrating it into a webform.

That’s it, I won’t explain how you add a library as it is documented already (see my first link to the official documentation).

Posted in Web Development and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.