If you’re creating a form using Drupal and find you want to add some javascript or CSS then you can use the “#attached” attribute to do so. Using “#attached” you can include local javascript/CSS files, external javascript/CSS files, or inline styles and scripts. You can also use drupal_add_js() to include a script but this is not recommended. First, drupal_add_js() is deprecated in Drupal 8 so you are only putting roadblocks in your way for a future upgrade. Second and more importantly, drupal_add_js() adds the script to the form page, but it does not allow any modules to interact with the JS using hook_form_alter().
  

Local Files

To include a local javascript or CSS file, include your files in an array with a key of “js” or “css” to the “#attached” array. It’s good practice to use drupal_get_path() to get the parent directory file path.

  

External Files

It’s possible to include external files as well, here’s how.

  

Inline

You can include inline scripts and styles as well. If you have a small snippet there’s not really a need to create a file.

  

Drupal Libraries

Drupal includes a number of libraries, here’s how to use them.

4 comments on “Include Javascript or CSS to a Drupal Form using #attached

  1. pest away says:

    I enjoy, lead to I found just what I used to be taking a look for.
    You have ended my 4 day long hunt! God Bless you man. Have a nice day.
    Bye

  2. shadow wordpress theme says:

    It’s…. REALLY amazing *.* !!! thank you so much…

  3. Myko says:

    For me attachment of the CSS working by method below

    ‘css’ => array(
    array(
    ‘data’ => ‘css/default_style.css’,
    ‘type’ => ‘file’
    ),
    ),

  4. metsnerilya says:

    privet suka

Leave a Reply

Your email address will not be published. Required fields are marked *