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.