I have created a custom form using Drupal form API which have an ajax callback. The ajax callback is associated with a select box, which returns a container on change the dropdown. This is running perfectly.
But now, as per current requirement, I need to change the html of a specific div along with the previous operation, which means two actions inside a single callback. Please check my code and help me understand what should I do.
public function buildForm(array $form, FormStateInterface $form_state) { $form['store_state'] = array( '#type' => 'select', '#options' => $state_options, '#ajax' => array( 'callback' => '::getStoresByState', 'wrapper' => 'state-fieldset-container', 'event' => 'change', 'progress' => array( 'type' => '', 'message' => '', ), ), ); $form['select_cities_container'] = [ '#type' => 'container', '#attributes' => ['id' => 'state-fieldset-container'], ]; return $form; } public function getStoresByState(array $form, FormStateInterface $form_state) { $return_result = array(); $return_result['city_container'] = $form['select_cities_container']; $filtered_location_table = '<div class="filtered_table_by_state"><p>I WANT TO CHANGE THE TEXT HERE</p>'; $filtered_location_table .= '</div>'; $response = new AjaxResponse(); $response->addCommand( new HtmlCommand( '.filtered_store_location', '<div class="filtered_location_table">'.$filtered_location_table.'</div>'), ); $return_result['filtered_store_locations_by_state'] = $response; return $return_result; }
As the function returns $form['select_cities_container']
& $response
at once, so I tried to wrap them in an array and return it at the end, but unfortunately only $form['select_cities_container']
returns and $response
is not returned.
If I perform single action on this callback, it’s working fine.
public function getStoresByState(array $form, FormStateInterface $form_state) { return $form['select_cities_container']; }
It’s also working
public function getStoresByState(array $form, FormStateInterface $form_state) { $filtered_location_table = '<div class="filtered_table_by_state"><p>I WANT TO CHANGE THE TEXT HERE</p>'; $filtered_location_table .= '</div>'; $response = new AjaxResponse(); $response->addCommand( new HtmlCommand( '.filtered_store_location', '<div class="filtered_location_table">'.$filtered_location_table.'</div>'), ); return $response; }
How will I return both at once?