Drupal 8 Form update text field value with AJAX
How to update text field value with AJAX
Bellow example will demonstrate, how to update text field value with ajax. In your hook_form_alter use:
// Create find coordinate button.
$form['field_gc_coordinates']['widget'][0]['subform']['#attributes'] += ['id' => 'lat-long-wrapper'];
$form['field_gc_coordinates']['widget'][0]['subform']['field_city_name']['field_btn_cord'] = [
'#type' => 'button',
'#value' => 'Get Coordinates',
'#ajax' => [
'callback' => '\Drupal\gc\Controller\AjaxHandlerController::getCoordinates',
'event' => 'click',
'wrapper' => 'lat-long-wrapper',
'progress' => [
'type' => 'throbber',
'message' => t('Please wait while fetching coordinates...'),
],
],
];
In your AjaxHandlerController:
public function getCoordinates(array &$form, FormStateInterface $form_state) {
$form['field_gc_coordinates']['widget'][0]['subform']['field_latitude']['widget'][0]['value']['#value'] = latitude_val;
$form['field_gc_coordinates']['widget'][0]['subform']['field_longitude']['widget'][0]['value']['#value'] = longitude_val;
return $form['field_gc_coordinates']['widget'][0]['subform'];
}

Comments
Post a Comment
There is comment posted on your blog, chandu7929@blogpost.com