36

I need to add some external and local CSS and JavaScript files to a form, but I can't seem to find the right way to do this. Do I simply add the paths and URLs for the JS and CSS files?

I assume $form['#attached']['css'][] and $form['#attached']['js'][] are the correct places to do this, so they get reloaded on form rebuilds. I seem to be missing something.

70

Have you looked at the documentation?

Attach CSS and JS to form

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached

$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';

$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';

External files

http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_attached/7

External 'js' and 'css' files can also be loaded. For example:

$build['#attached']['js']['http://code.jquery.com/jquery-1.4.2.min.js'] = array('type' => 'external');
  • I have. Can you tell me where it references how to handle external CSS files? – vintorg Apr 15 '13 at 20:31
  • Go to api.drupal.org/api/drupal/includes%21common.inc/function/… and search for 'External'. – Alex Gill Apr 16 '13 at 10:54
  • 2
    Just a note - you can add JavaScript as described above to specific form by adding function named <module name>_form_<form id>_alter to your module. Finding form id is described here: drupal.stackexchange.com/questions/5802/… – Nux Apr 22 '15 at 16:28
  • 1
    This example is kinda bad because you're assuming this will be the ONLY attachment on the form! – doublejosh Mar 19 '16 at 0:44
  • 6
    Comment by doublejosh means: usually one should append to the array rather than replacing it. So the example should be $form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css'; etc.. – tanius Jul 12 '16 at 14:48
11

Here's the method for adding inline CSS to forms...

$form['#attached']['css'][] = array(
  'data' => '.my-example-element { display: none; }',
  'type' => 'inline',
);

Note that you should add to the css array rather than replace it. Meaning you should use: ['css'][] = rather than ['css'] = to avoid squashing other additions.

6

Here is one way to do this that is via. calling a function using #after_build property. Just pass in your form id in switch case.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_form':
      $form['#after_build'][] = 'mymodule_after_build';
      break;
  }
}

function mymodule_after_build($form, &$form_state) {
  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js ("$path/mymodule.js");
  return $form; 
}

Also you can follow this good tutorial Adding css and js to drupal forms

Hope this helps. :)

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.