I have been trying to learn Drupal forms with AJAX recently and from my current understanding of it I thought I should be able to do something like presented below (I wanted to store all selected values as a string in another hidden field to grab it later in my JS and do some stuff, but that does not matter here, what matters is what I do not get about AJAX).

So the idea is that selecting checkboxes will update the value in the input field with checkboxes' values.

Unfortunately, the #default_value on my textfield is not being set on my page, even though I can see it being set in my $form array when debugging with xdebug.

The form is used to filter some results with an AjaxResponse() ReplaceCommand.

Here is the simplified code, stripped from most unrelated things:

public function buildForm(array $form, FormStateInterface $formState)  {
  $values = $formState->getValues();
  $defaultCountry = implode(':', array_filter($values['countryId']));
  $form['countryId'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Country'),
    '#options' => [
      '1' => 'Aaa',
      '2' => 'Bbb',
      '3' => 'Ccc',
    '#ajax' => [
      'callback' => '::ajaxResponse',
      'event' => 'change',
      'wrapper' => 'some-wrapper-for-filters-form-and-results',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
  $form['defaultCountry'] = [
    '#type' => 'textfield',
    '#title' => $this->t('TEST'),
    '#default_value' => $defaultCountry,
  return $form;

public function ajaxResponse(array &$form, FormStateInterface $formState) {
  $result = 'some processing logic';
  $response = new AjaxResponse();
    ->addCommand(new ReplaceCommand('.filtered-offers > div', $result));
  return $response;

What do I miss here?


While I'm not sure why it doesn't work, the fix I've found in the past is to set the default value as #value in the AJAX callback. While this generally goes against the principle of #AJAX in Drupal (ie - changes should be made in the form definition), it works.

  • Can't make it work that way either. With/without setting default value in buildForm first, nor with returning $response in AJAX callback, nor with returning $form in AJAX callback (tested on just setting it to some explicit string instead of my variable). Ran out of ideas.
    – KrzysiekK
    Aug 24 '18 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.