[development] Using AHAH to load a default set of fields and values

Andrew Berry andrewberry at sentex.net
Wed Jan 19 01:41:41 UTC 2011


On 2011-01-18, at 6:43 PM, Jeff Hartman wrote:

> I have a particular content type where I have a vocabulary/taxonomy drop down. I am using hook_form_alter to modify this menu to use ahah in order to query the db for a bunch of default values to populate other portions of the form.

#default_value is the way to go. My guess is that the ordering of your module is causing another module to set #default_value after yours does. Dropping the weight of your module will likely fix the issue.

I've been working on AHAH forms as well, and ended up writing this helper function to set default values. Call it at the end of your form callback and it will populate default values based on the current state of the form.

Cheers,
--Andrew

/**
 * FAPI helper function to set default values.
 *
 * This is especially useful when going back and forward in a multistep form,
 * or when editing existing data.
 *
 * To use this function, pass in an array of values, such as
 * $form_state['storage']['values'][$current_step], and each element will have
 * #default_value set in-place. Any elements with the autocomplete attribute
 * set will not be populated (as the only valid value for autocomplete is
 * "off").
 *
 * @param $form_values
 *   An array of form values, keyed by elements.
 * @param &$element
 *   The form element to set the default values for.
 */
function mymodule_form_default_values($form_values, &$element) {
  foreach (element_children($element) as $child) {
    if (isset($form_values[$child])) {
      if (array_key_exists('#attributes', $element[$child]) && array_key_exists('autocomplete', $element[$child]['#attributes'])) {
        continue;
      }
      // Don't override pre-existing defaults.
      if (isset($element[$child]['#default_value'])) {
        continue;
      }
      $element[$child]['#default_value'] = $form_values[$child];
    }
    mymodule_form_default_values($form_values[$child], $element[$child]);
  }
}


-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2488 bytes
Desc: not available
Url : http://lists.drupal.org/pipermail/development/attachments/20110118/a8feabb3/attachment-0001.bin 


More information about the development mailing list