PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

1 Mar 2017

Update multiple fields using #ajax in Drupal 7 form

     We know how to replace a field using #ajax in a form. Can we update multiple fields using #ajax in a form? Yes, we can update multiple fields using #ajax in the Drupal 7. We can achieve it using ajax_command_replace() in Drupal 7. For more details about ajax commands on Drupal 7, please visit https://api.drupal.org/api/drupal/7.x/search/ajax_command.

Update fields using #ajax in a Drupal form:


    Consider the following example. In this example, I've created a form with fields First, Second & Third name. I tried to update the Second & Third name fields when focus out on the First name field.

/**
 * Implments hook_form()
 */
function phponwebsites_ajax_form($form, &$form_state) {
  $form['firstname'] = array(
    '#title' => t('First name'),
    '#type' => 'textfield',
    '#ajax' => array(
      'callback' => '_generate_textfield',
      'wrapper' => 'copied-text-field',
    )
  );

  $form['secondname'] = array(
    '#title' => t('Second name'),
    '#type' => 'textfield',
    '#prefix' => '<div id="copied-secondname">',
    '#suffix' => '</div>',
  );

  $form['thirdname'] = array(
    '#title' => t('Third name'),
    '#type' => 'textfield',
    '#prefix' => '<div id="copied-thirdname">',
    '#suffix' => '</div>',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );

  return $form;
}

function _generate_textfield($form, &$form_state) {
  if (!empty($form_state['values']['firstname'])) {
    $form['secondname']['#value'] =  $form_state['values']['firstname'];
    $form['thirdname']['#value'] =  $form_state['values']['firstname'];
  }
  $commands = array();
  $commands[] = ajax_command_replace('#copied-secondname', drupal_render($form['secondname']));
  $commands[] = ajax_command_replace('#copied-thirdname', drupal_render($form['thirdname']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

When you tried to execute the above codes, it'll populate the same name on the other 2 fields. It looks likes the below image:

Update multiple form fields using #ajax in Drupal 7


Now I hope you know how to populate multiple fields using #ajax in Drupal 7 forms.