I'm building a custom module (say 'mycalc') with a custom block with a custom form inside. Now I want to attach a library to the form and add some styling and live manipulation.

I created the mycalc.libraries.yml like this:

  version: 1.x
      css/mycalc.css: {}
    js/mycalc.js: {}
    - core/jquery

I added the js/mycalc.js and css/mycalc.css files with few basic lines. Then in the src/Form/MyCalcForm.php (where is set the MyCalcForm class), i edited the buildForm method adding this just before the return():

$form['#attached']['library'][] = 'mycalc/myform';

But there's no js nor css loading. What's wrong? Please help!

  • 1
    First things first, did you clear the cache? – Kevin Jan 20 '18 at 17:55
  • 1
    @Kevin Yes, of course. Both with drush cr and via web interface. – nessunluogo Feb 21 '18 at 11:27

You need to attach library in your hook_form_alter():

* Implements hook_form_alter().

function <YOUR_MODULE_NAME>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    /*Attach library, for Blazy implementation you will need
       $form['#attached']['library'][] = 'blazy/load';
    $form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';
    $form['#attached']['library'][] = '<YOUR_MODULE_NAME>/<library_name>';
    /*Pass even variable from this function to JS settings*/
    $form['#attached']['drupalSettings']['<YOUR_MODULE_NAME>']['<route_name>'] ['variable'] = 'PHP Value To JS';

    return $form;

If you pass variable with above mentioned method - $form['#attached']['drupalSettings']['<YOUR.... then that variable will be available in your JS file.

(function ($, Drupal, window) {
  Drupal.behaviors.helpers = {
    attach: function (context, settings) {
      'use strict';

       console.log(settings.variable); //Should log variable value
})(jQuery, Drupal, window);

Add javascript to form by module

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.