Ajax form element callback

Components

To save the API token field without submitting the form, you can add a simple ajax callback function. In this example, we are saving the field value on the keyup event, but you can also use the change event or if you have an autocomplete field then you probably want to use the autocompleteclose event.

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Form\FormStateInterface;

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['api_token'] = [
    '#type' => 'textfield',
    '#title' => $this->t('API token'),
    '#ajax' => [
      'callback' => '::updateApiToken',
      'event' => 'keyup',
    ],
  ];

  return parent::buildForm($form, $form_state);
}

public function updateApiToken(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $this->config('MY_MODULE.settings')
    ->set('api_token', $form_state->getValue('api_token'))
    ->save();
  return $response;
}

About the Author

Goran Nikolovski is a senior developer with over 10 years of experience turning ideas into scalable digital products—from web platforms and mobile apps to AI-powered tools. He is passionate about clean code, creative problem-solving, and shaping the future of digital development.

AI Assistant