5

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

sync_script:
  version: 1.x
  js:
    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?

21

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:

<route_name>:
  version: 1.x
  js:
    js/<your_javascript_file>.js: {}
  dependencies:
    - 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>/<route_name>';
    $form['#attached']['drupalSettings']['<module_name>']['<route_name>'] ['variable'] = 'value';

    return $form;

}

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

(function($){
    console.log(drupalSettings.<module_name>.<route_name>.variable); // value
})(jQuery);

Hope this help!

  • 1
    Please, use behaviors, see drupal.org/node/756722#behaviors – rpayanm Feb 24 '17 at 17:59
  • 4
    I think route_name would probably be better called library_name, since it has nothing to do with routing. – mikl Jun 4 '18 at 11:38

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.