i am writing a module in drupal 8. I wish to add a javascript when loading that form.

function ajax_example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#attached']['library'][] = array('ajax_example', 'ajax_example.sync_script');

and i have defined the following at the module library yml file

  version: 1.x
    js/test.js: {}

but seems the js is not embedded. And i have put the js in a folder called js at the root directory of the module.

What is the way for drupal 8 to embed a javascript at the form?

1 Answer 1


I don't know what you're aiming to build.

Because I think it's not good to use your javascript in hook_form_alter() , that way, any form you try to see will invoke that javascript code.

However... Back to your issue,

I think the hook_form_alter() function should be used in the module_name.module file under the root of your module folder: modules/custom/module_name/module_name.module along side the routing, info, etc.

After building the .module file, you need to build the module_name.libraries.yml file (if it's not already built), and there, you write your routing requirements, example:

  version: 1.x
    js/<your_javascript_file>.js: {}
    - core/jquery
    - core/drupalSettings

Backto the .module file, you implement the hook_form_alter, so your code goes like this:

 * Implements hook_form_alter().
function <module_name>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    $form['#attached']['library'][] = '<module_name>/<library_name>';
    $form['#attached']['drupalSettings']['<module_name>']['<library_name>']['variable'] = 'value';

To make sure, console.log your PHP variable in your_javascript_file to see it, example:

    console.log(drupalSettings.<module_name>.<library_name>.variable); // value

Hope this helps!

  • 1
    Please, use behaviors, see drupal.org/node/756722#behaviors
    – rpayanm
    Feb 24, 2017 at 17:59
  • 6
    I think route_name would probably be better called library_name, since it has nothing to do with routing.
    – mikl
    Jun 4, 2018 at 11:38
  • To alter only a single form, you can use implement hook_form_FORM_ID_alter()
    – mbomb007
    Nov 14, 2022 at 20:58

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.