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 />

Defining a library with hook_library<br />

When a module has a library or plugin it wants to use or make available to other<br />

libraries, it should define it as a library using hook_library(). Since we have a<br />

JavaScript file and CSS file in our Hello World module, we can add it as a library<br />

in the following way:<br />

/**<br />

* Implements hook_library().<br />

*/<br />

function hello_world_library() {<br />

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

$libraries = array();<br />

$libraries['hello_world_library'] = array(<br />

'title' => 'Hello World',<br />

'website' => 'http://example.com',<br />

'version' => '1.0',<br />

'js' => array(<br />

$path . '/hello_world.js' => array(),<br />

),<br />

'css' => array(<br />

$path . '/hello_world.css' => array(),<br />

),<br />

'dependencies' => array(<br />

array('system', 'ui.dialog'),<br />

),<br />

);<br />

return $libraries;<br />

}<br />

The title, website, and version properties are used to define meta data about<br />

the libraries. This is important when looking for information, documentation, and<br />

checking for updates to a library.<br />

The js, css, and dependencies do all the work. If any dependencies are defined,<br />

they are added before the JavaScript and CSS defined here. Then the JavaScript<br />

and CSS are added with the key for each line being the first argument for either<br />

drupal_add_js() or drupal_add_css() and the value being the options argument<br />

for each of the corresponding functions.<br />

<strong>Drupal</strong> has three special dependencies that are added which do not need to<br />

be defined. They are jquery.js, jquery.once.js, and drupal.js. These are<br />

added to the page when the first call to drupal_add_js() is made or when<br />

drupal_add_library() is first called.<br />

[ 296 ]

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

Saved successfully!

Ooh no, something went wrong!