How to update multiple fields using ajax?

by Sudha Bisht   Last Updated December 14, 2017 14:07 PM

In content type there are three field . Each field are node reference to different content. Here I want to restrict value and create dependency on these field. For example: I have one auto complete field "Country". On change of "Country", select list(i.e. State) field value is updated. On change of "State", "county" field is updated. Everything is working fine.

When I change value of "Country", "State" value get change But "county" value hold previous value. How should I achieve this. How should I reset value of county

My code snippet is like

function module_form_alter(&$form, &$form_state, $form_id) {
  $form['field_country'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => '_state_list_callback',
    'event'    => 'change',
    'wrapper' => 'state-list',
    'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'),
);
  $form['field_country']['#prefix'] = '<div id="state-list">';
  $form['field_country']['#suffix'] = '</div>';

  $form['field_state'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => '_county_list_callback',
    'event'    => 'change',
    'wrapper' => 'county-list',
    'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'),
);
  $form['field_county']['#prefix'] = '<div id="county-list">';
  $form['field_county']['#suffix'] = '</div>';
}


function _county_list_callback(&$form, &$form_state) {
  return $form['field_county'];
}

function _state_list_callback(&$form, &$form_state) {
  return $form['field_state'];
}
Tags : hooks ajax


Answers 1


You can use ajax_command_replace() when replacing more than one element/field. Check this ans. The answer says as:

Instead of returning the HTML of the single element to update, your ajax callback can return an array of ajax commands. So it can return two ajax_command_replace to replace each element.

Yogesh
Yogesh
January 10, 2017 07:47 AM

Related Questions




Ajax button doesn't work

Updated February 17, 2017 15:07 PM

AJAX request from a hook_node_postinsert

Updated September 15, 2017 13:07 PM

I want to make ajax call to module functuion

Updated September 01, 2018 09:07 AM