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

Popular posts from this blog

How to setup Drupal 8 Multisite on nginx webserver with different domain.

Install drush globally using composer on WSL

Drupal views create exposed filter programmatically