Drupal 8 - Run Javascript & CSS from form

By xngo on March 8, 2019

Overview

In Drupal 8, stylesheets (CSS) and JavaScript (JS) files need to be defined as an asset library before they can be used. Then, you attach that asset library to page, form, preprocess function, twig template, etc. For this tutorial, I'm attaching CSS & JS in a form.

Define asset library

In ./modules/tradesteps/tradesteps.libraries.yml, define your asset library like the following:

# Create library asset name
trade-steps:
  version: 1.x
  css:
    layout:
      css/trade-steps-layout.css: {}
    theme:
      css/trade-steps-theme.css: {}
  js:
    js/trade-steps.js: {}
 
  # Add core Drupal Ajax library as a dependency for this library.
  dependencies:
  - core/jquery

Create CSS & JS files

In ./modules/tradesteps/css/trade-steps-layout.css, add

.result_message{
    color: red;
}

In ./modules/tradesteps/css/trade-steps-theme.css, add

.result_message{
    color: green;
}

In ./modules/tradesteps/js/trade-steps.js, add

(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
 
      // Add your Javascript code here.
      $('.result_message', context).css('background', 'yellow');
 
    }
  };
})(jQuery, Drupal);

Attach your asset library to the form

To attach your asset library, simply add the following statement in the buildForm() function of your form class:

$form['#attached']['library'][] = 'YOUR_MODULE_NAME/YOUR_ASSET_LIBRARY_NAME';

Here is the full example from my ./modules/tradesteps/src/Form/MyFormRunJs.php file

<?php
namespace Drupal\tradesteps\Form;
 
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
 
// Use for Ajax.
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
 
class MyFormRunJs extends FormBase {
 
    /**
    * Build the simple form.
    */
    public function buildForm(array $form, FormStateInterface $form_state) {
 
        // Add input field called title.
        $form['title'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Title'),
            '#required' => TRUE,
        ];
 
        // Attach Ajax callback to the Submit button.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#ajax' => [
                'callback' => '::setMessage',
            ],
        ];
 
 
        // Placeholder to put the result of Ajax call, setMessage().
        $form['message'] = [
            '#type' => 'markup',
            '#markup' => '<div class="result_message"></div>',
        ];
 
        // Add your asset library here.
        $form['#attached']['library'][] = 'tradesteps/trade-steps';
 
        return $form;
    }
 
    public function setMessage(array $form, FormStateInterface $form_state) {
 
        $response = new AjaxResponse();
        $response->addCommand(
            new HtmlCommand(
                '.result_message',
                '<div class="my_message">Submitted title is ' . $form_state->getValue('title') . '</div>')
            );
        return $response;
    }
 
    /**
    * Implements a form submit handler.
    */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Nothing to do. Use Ajax.
    }
 
    public function getFormId() {
        return 'tradesteps_simple_form_run_js';
    }
 
}

Test the input form

  1. Clear your cache.
  2. Open http://your-domain.com/my_form_run_js
  3. Type in your title and then click on the Submit button.

Run CSS & JS from form screenshot

Github

  • https://github.com/xuanngo2001/drupal-form-attach-js-css.git

Reference

  • https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
  • https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.