18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The following code adds a system CSS file which is not preprocessed and is only<br />

used for screen:<br />

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

$options = array(<br />

'group' => CSS_SYSTEM,<br />

'media' => 'screen',<br />

'preprocess' => FALSE,<br />

);<br />

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

Passing variables from PHP to JavaScript<br />

<strong>Drupal</strong> provides a means of passing variables from PHP to JavaScript using<br />

drupal_add_js(). Many applications want to pass configuration information<br />

to JavaScript that runs on a page. This function is the means in <strong>Drupal</strong> to pass<br />

that information easily.<br />

Chapter 10<br />

<strong>Drupal</strong> calls the variables passed from PHP to JavaScript settings. A simple example<br />

of a setting that passes the text "Hello World!" from PHP to JavaScript would<br />

look like:<br />

drupal_add_js(array('helloWorld' => "Hello World!"), 'setting');<br />

Variable names in the PHP portion of <strong>Drupal</strong> are in lowercase with<br />

an underscore separating words. In JavaScript they should be in<br />

lowerCamelCase. For more information see the coding standard at<br />

http://drupal.org/coding-standards.<br />

JavaScript can access this at <strong>Drupal</strong>.settings.helloWorld. For example the<br />

following JavaScript would display the "Hello World" as a pop-up:<br />

alert(<strong>Drupal</strong>.settings.helloWorld);<br />

Settings are unlike other uses of drupal_add_js(). They are added to the page<br />

in the header with a weight of JS_LIBRARY. There are no other options besides<br />

specifying that it is a setting, as shown in the following example:<br />

drupal_add_js(array('hello_world' => "Hello World!"), 'setting');<br />

[ 293 ]

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

Saved successfully!

Ooh no, something went wrong!