You are here

prepopulate.module in Prepopulate 6

Fill form elements with data from GET values.

Originally written by ea. Farris <eafarris@gmail.com> Based on an idea from chx, from the conversation at http://www.drupal.org/node/27155.

File

prepopulate.module
View source
<?php

/**
 * @file
 * Fill form elements with data from GET values.
 *
 * Originally written by ea. Farris <eafarris@gmail.com>
 * Based on an idea from chx, from the conversation at
 * http://www.drupal.org/node/27155.
 */

/**
 * Implementation of hook_help().
 */
function prepopulate_help($path, $arg) {
  switch ($path) {
    case 'admin/modules#description':
      return t('Pre-populates forms with HTTP GET data');
      break;
  }
}

/**
 * Implementation of hook_form_alter().
 */
function prepopulate_form_alter(&$form, $form_state, $form_id) {
  if (isset($_REQUEST['edit'])) {
    foreach (array_keys((array) $_REQUEST['edit']) as $getvar) {
      if (element_child($getvar) && !is_null($form[$getvar])) {
        _prepopulate_get_walk($form[$getvar], $_REQUEST['edit'][$getvar]);
      }
    }
  }
}

/**
 * Internal helper to set element values from the $_GET variable.
 *
 * @param &$form
 *   Array. A form element.
 * @param &$getslice
 *   String or array. Value(s) to be applied to the element.
 */
function _prepopulate_get_walk(&$form, &$getslice) {
  if (is_array($getslice)) {
    if (!is_null($form['#default_value'])) {
      if (!is_array($form['#default_value'])) {

        // Something went wrong so stop here.
        return;
      }
      $form['#default_value'] = array_merge($form['#default_value'], $getslice);
    }
    else {
      foreach (array_keys($getslice) as $getvar) {
        if (element_child($getvar) && is_array($form) && !is_null($form[$getvar])) {
          _prepopulate_get_walk($form[$getvar], $getslice[$getvar]);
        }
      }
    }
  }
  else {
    $form['#default_value'] = $getslice;
  }
}

Functions

Namesort descending Description
prepopulate_form_alter Implementation of hook_form_alter().
prepopulate_help Implementation of hook_help().
_prepopulate_get_walk Internal helper to set element values from the $_GET variable.