[development] fixing nodeapi : programmatically submitting forms.

Nedjo Rogers nedjo at islandnet.com
Fri Jul 14 19:56:56 UTC 2006


> Karoly Negyesi wrote:
>>>  >> function mymodule_forms() {
>>>  >>    $form['mymodule/form_id'] = array(
>>>  >>         'callback' => 'mymodule_form_id',
>>>  >>         'access' => user_access('can do form_id'),
>>
>> *snip* doing this is blatantly easy. I actually have the script that
>> changes a return drupal_get_form to a hook forms array. Will post the
>> code later in case anyone is interested.
>
> yes, please share this script.

A couple of tangentially related snippets:

1. Learn about all available forms, with an address they can be fetched at:

/**
 * Implementation of hook_form_alter().
 *
 * Register available forms into an array variable.
 */
function jstools_form_alter($form_id, &$form) {
  // If this form_id is not already registered, register it.
  $options = variable_get('jstools_forms_options', array());
  if (!array_key_exists($form_id, $options)) {
    $options[$form_id] = $_GET['q'];
    variable_set('jstools_forms_options', $options);
  }
}

2. Fetch a form in JSON format. This is code we're looking at using in the 
formbuilder module.

/**
 * Implementation of hook_form_alter().
 *
 * Redirect a page request to output a given form in JSON format.
 *
 * This method depends on a form_alter done in jstools.module, where the
 * variable 'jstools_forms_options' is populated with an array of available
 * forms in the format 'form_id' => 'path'. If desired, relevant code could
 * be copied from jstools_form_alter() to remove this dependency.
 *
 * To use this method, a javascript call needs to issue an AJAX page request
 * appending a 'formbuilder_form' form_id value to the URL in GET encoding.
 * The corresponding form will be returned in JSON encoding.
 */
function example_form_alter($form_id, &$form) {
  // If the formbuilder has been called, redirect the form output.
  if (!empty($_GET['example_form']) && ($_GET['example_form'] == $form_id)
&& (user_access('load forms')) {
    if (is_array($form['#pre_render'])) {
      $form['#pre_render'][] = 'example_dispatch';
    }
    else {
      $form['#pre_render'] = array('example_dispatch');
    }
  }
}

/**
 * Send a form as a Javascript object in JSON notation.
 */
function example_dispatch($form_id = NULL, $form = NULL) {
  if (user_access('load forms')) {
    drupal_set_header('Content-Type: text/javascript');
    print 'var form = '. drupal_to_js($form) .";\n";
  }
  exit();
}



More information about the development mailing list