18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JavaScript in <strong>Drupal</strong><br />

This provides for adding a file in the simplest form. In the case of adding a file, the<br />

first argument is always the path to the file. Paths to the files within the <strong>Drupal</strong><br />

installation are relative to the base path of the site. When these files are displayed<br />

in the browser the base path will be added to the path of the file within <strong>Drupal</strong>.<br />

Since modules can live in more than one place within the file system, the function<br />

drupal_get_path() can be used to get the path of the module providing the file.<br />

Rewriting the examples above to point to the module's location in the file system<br />

dynamically, we would write:<br />

$path = drupal_get_path('module', 'hello_world');<br />

drupal_add_js($path . '/hello_world.js');<br />

drupal_add_css($path . '/hello_world.css');<br />

For more information on using drupal_get_path() with modules,<br />

themes, and other systems within <strong>Drupal</strong>, see the API documentation at<br />

http://api.drupal.org/api/function/drupal_get_path/7.<br />

In this simple example, we are only passing in the $data argument, in this case the<br />

file name, because <strong>Drupal</strong> defaults to adding files. The second argument is called<br />

$options and can accept either a string with the type JavaScript or CSS being added,<br />

or an array of options. Adding this JavaScript in more detail could be re-written as:<br />

$path = drupal_get_path('module', 'hello_world');<br />

drupal_add_js($path . '/hello_world.js', 'file');<br />

drupal_add_css($path . '/hello_world.css', 'file');<br />

While dealing with files, the second argument can be set to 'file' for files internal<br />

to the <strong>Drupal</strong> filesystem or at a relative path URL, and 'external' for files outside<br />

the <strong>Drupal</strong> installation.<br />

The $options argument can be used to set several other options for each file<br />

including weight, group, every_page, scope, defer, preprocess, and caching.<br />

JavaScript files are rendered based on group, whether they are on every page, and<br />

then by weight. The JavaScript groups are JS_LIBRARY, JS_DEFAULT, and JS_THEME.<br />

Within each group files are sub-grouped by whether every_page is set to true.<br />

Scripts on every page are listed before files on some pages. Finally, within each subgroup<br />

files are ordered by weight.<br />

[ 290 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!