Drupal - Adding CSS and JS to form with attachments

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');

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.


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. :)

Tags:

Forms

7