0

Problem: After an AJAX callback, the text is not inserted in the body field.

Description: I created a fresh Drupal installation. Added a field 'Type' | field_type | List (text) to the Article CT. The goal was that a change in that select would add text to the body field. Here's the ajax_test.module code, inspired by the documentation:


use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter()
 */
function ajax_test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === 'node_article_form') {

    $form['body']['#prefix'] = '<div id="edit-body-wrapper">';
    $form['body']['#suffix'] = '</div>';

    $form['field_type']['widget']['#ajax'] = [
      'callback' => 'myAjaxCallback',
      'disable-refocus' => FALSE,
      'event' => 'change',
      'wrapper' => 'edit-body-wrapper',
      'progress' => [
          'type' => 'throbber',
          'message' => t('Updating'),
      ],
    ];
  }
  // Outside the AJAX callback, the default_value works
  // $form["body"]["widget"][0]["#default_value"] = 'test';
}


function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  if ($selectedValue = $form_state->getValue('field_type')) {
    $form["body"]["widget"][0]["#default_value"] = 'test';
    // Here it won't
  }
  return $form['body'];
}

If I set the default_value without the AJAX, it appears correctly. Using Xdebug, I can see that the callback is updating the value correctly, but nothing appears in the body on completion.

Any suggestions would be very appreciated.

3
  • I forgot to copy a part of the code that sets the wrapper id. Since I can't edit it, here it is: $form['body']['#prefix'] = '<div id="edit-body-wrapper">'; $form['body']['#suffix'] = '</div>'; Feb 7 at 17:10
  • The original author of a question or answer may always edit their own post, regardless of reputation level.
    – cilefen
    Feb 7 at 19:21
  • Thank you. Somehow I missed it before. Edited. Feb 8 at 1:05

1 Answer 1

0

I finally found out a solution here: AJAX form - replacing #default_value not working (the '2021 edit...') In this specific case, the callback would work:

function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('field_type')) {
    $userInput = $form_state->getUserInput();
    unset($userInput["body"]);
    $form_state->setUserInput($userInput);
    $form["body"]["widget"][0]["#default_value"] = 'test';
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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