I have two Drupal modules.

One is a shared module that provides a JavaScript library. The second is a module that builds a form which uses that library.

Lets call them modlib and modform.

They've been written separately because the JS library needs to be used in multiple places, on various different forms, in different parts of the system.

This is working well. I can reference the JS code in modlib from within modform using $form['#attached']['library'].

However modlib also includes some configuration which needs to be loaded into drupalSettings.modlib for use within the JavaScript code. This isn't being loaded, and I'm unsure how to make it load from within modform.

Can anyone help? Thank you.


Never mind, I solved it.

I've added a preprocess_node function to the module file of modlib, which looks a bit like this:

function mymodule_preprocess_node(&$variables)
    $apikey = \Drupal::configFactory()->getEditable('mymodule.apikeyconfig')->get('api_key');
    $variables['#attached']['drupalSettings']['mymodule']['pca'] = ['key' => $apikey];

So now the config value is being added to drupalSettings on every page load.

This is maybe not ideal (ideal would be only loaded when a relevant form is on the page), but it's good enough and means I don't have to have any logic in modform to load the config.

  • 2
    If you move these 2 lines back into your form and change "$variables" for "$form" like you had with your other example that should do the trick and will only be included when your form is – Leigh Oct 8 '18 at 12:30

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.