Skip to main content
Please don't use Drupal version tags in title
Link
leymannx
  • 18.8k
  • 6
  • 72
  • 126

D8 - Why can't I change textfield #default_value based on checkboxes' values after an AJAX response?

Source Link

D8 - Why can't I change textfield #default_value based on checkboxes' values after an AJAX response?

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();
  $response
    ->addCommand(new ReplaceCommand('.filtered-offers > div', $result));
  return $response;
}

What do I miss here?