Jun 07, 2019 in Drupal 8, Snippets

The way of handling javascript and css is different from drupal 7. Instead of putting all your javascript in your theme, you should specify the javascript to appear only on the places where it is necessary. This snippet shows how to do it.

First, you need to define your javascript in a custom library. In your module, add a file named mymodule.libraries.yml and add the following:

    js/customform.js: {}
    - core/jquery
    - core/drupal

In your custommodule.module file, hook in to the form and attach the libary: 

 * @param $form
 * @param FormStateInterface $form_state
 * @param $form_id
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   * Custom javascript for the search form
  if($form['#id'] == 'MYFORM') {
    $form['#attached']['library'][] = 'mymodule/custom';

Clear caches and the file is added, only when the form is rendered.