21st May 2012

How to use $form['#attached'] with a JavaScript setting in Drupal 7 Form API

Alli Price

"You're entering a realm which is ...unusual, maybe it's magic. That contains some kind of monster, the second one... Prepare to enter, The Scary Door."

If none of that makes any sense, watch the video at the end of the post. This is a little how I felt wrangling with #form attachments.

A pre-cursor, you can use drupal_add_js() to add JavaScript to your forms, but if your form gets submitted and has errors, the regenerated form will be missing your JavaScript added via drupal_add_js(), which is why we have #attached.

We all know and love drupal_add_js(), however I myself am not totally grounded with Form attachments. Throwing in a local or external file is easy enough, as is inline, though I had trouble with settings.

A fun point in my fumblings was the ridiculous thought of attempting to use an Array as an index for an Array.... Thought better of it (this isn't actually possible anyway).

After traversing drupal_render(), and then drupal_process_attached() I found this:

// In some cases, the first parameter ($data) is an array. Arrays can't be // passed as keys in PHP, so we have to get $data from the value array. 

Ah, and so just use an index then, much more sensible! Here's how you use form attached with a JavaScript setting array.

$form['#attached']['js'][] = array( 'data' => array( 'xx_system' => array( 'xx_code' => variable_get('xx_code', 'xx'), 'xx_key' => variable_get('xx_key', 'xx'), ), ), 'type' => 'setting', );