First of all check for typos since, after failing to clear the cache is the most common mistake in this use case. After that, depending on your form base class attaching the library on the ::buildForm()
method should suffice. Also worth noting that perhaps another module (custom or contrib) could be messing with your form render array.
In the case you need to attach library to a form from core or third-party, you need to implement a hook_form_alter()
:
/**
* Implements hook_form_alter().
*/
function <YOUR_MODULE_NAME>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
// If your library is intended to be used on specific form
// check for it using the $form_id argument against your
// form id which in most cases is returned by the ::getFormId()
// method of your form.
if ($form_id !== '<YOUR_FORM_ID'>) {
// This is called eager return, is a technique
// to avoid code nesting to improve code readability.
return;
}
// To attach Blazy for example.
$form['#attached']['library'][] = 'blazy/load';
// To attach a library from a theme.
$form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';
// To attach a library from a module.
$form['#attached']['library'][] = '<YOUR_MODULE_NAME>/<library_name>';
// Pass even variable from this function to JS settings
$form['#attached']['drupalSettings']['<YOUR_MODULE_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) {
'use strict';
Drupal.behaviors.<YOUR_MODULE_NAME> = {
attach: function (context, settings) {
console.log(settings);
console.log(settings.variable); //Should log variable value
}
};
})(jQuery, Drupal);
Add javascript to form by module