Question

I have a form with a textfield element which when a user starts typing into I want to pre-populate a different element.

I've been using the #ahah attribute which works fine with the event property set to 'keyup' however I lose focus on the textfield element because the moment the 'keyup' event is fired the whole form is rebuilt due to ahah's behaviour.

I tried setting the event property to 'change' and that works nicely however in order for the 'change' event to fire I need to click away from the textfield - so from UI point of view I cannot expect users to click away from field just to get the results to display.

I'm not sure if it's possible to achieve what I want with AHAH which is fine but I'd like to stick with it if possible.

Happy to provide code if required and sorry if it's not clear, quite difficult to explain.

Thanks Steve

Was it helpful?

Solution

The whole form shouldn't be re-rendered by the browser. That's precisely the idea AHAH, that you can update just part of a form. Make sure to set the "wrapper" attribute (of the #ahah attribute) to the ID (as in: the HTML attribute) of the DOM element that you want Drupal's JS functionality to update asynchronously.

For example:

<?php
function MYMODULE_some_ahah_enabled_form(&$form_state) {

  $initial_markup = '<div>' . t('This content will be replaced') . '</div>';

  $form['dynamic_thing'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="dynamic-thing">', // Set Drupal's AHAH wrapper to this ID
    '#suffix' => '</div>',
    '#value' => $initial_markup,
  );

  $form['field_which_will_trigger_ahah_behavior'] = array(
    '#type' => 'textfield',
    '#ahah' => array(
      'path' => 'MYMODULE/path/to/ahah/callback',
      'wrapper' => 'dynamic-thing',
      'event' => 'keyup',
    ),
    '#default_value' => 'Change me',
  );

  return $form;
}

/**
 * Your menu callback (which is declared in your hook_menu()) which returns only the HTML that will replace the existing markup in $form['dynamic_thing'].
 */
function MYMODULE_ahah_callback() {
  $output = '<div>New content for the dynamic thing</div>';
  drupal_json(array('status' => TRUE, 'data' => $output));
  exit();
}

Your "field_which_will_trigger_ahah_behavior" DOM element in the browser shouldn't lose focus, or be re-rendered in any way, unless there's something else causing some bug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top