On this page
ReplaceCommand
Last updated on
18 December 2025
Ajax API
['#ajax']['wrapper']
This render array construct lists a callback that returns a render array. The rendered output from the render array is used to replace the element with an id matching the value of the wrapper element.
$config_types = [
'system.simple' => $this->t('Simple configuration'),
] + $entity_types;
$form['config_type'] = [
'#title' => $this->t('Configuration type'),
'#type' => 'select',
'#options' => $config_types,
'#default_value' => $config_type,
'#ajax' => [
'callback' => '::updateConfigurationType',
'wrapper' => 'js-config-form-wrapper',
],
];ReplaceCommand
$form['source_dependent'] = [
'#type' => 'container',
'#attributes' => ['id' => 'source-dependent'],
];
$form['source_dependent']['source'] = [
'#type' => 'select',
'#title' => $this->t('Media source'),
'#default_value' => $source ? $source->getPluginId() : NULL,
'#options' => $options,
'#description' => $source_description,
'#ajax' => ['callback' => '::ajaxHandlerData'],
'#required' => TRUE,
// Once the media type is created, its source plugin cannot be changed
// anymore.
'#disabled' => !$this->entity->isNew(),
];
// With this callback. The form calculates a number of children of $form['source_dependent'].
/**
* Ajax callback triggered by the type provider select element.
*/
public function ajaxHandlerData(array $form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#source-dependent', $form['source_dependent']));
return $response;
}
HTMX
In both cases the refactor is to code the form or controller to build the dynamic portion of the form in its normal build process. Often the ajax callback can be adjusted to accomplish this. HTMX attributes are added which cause the rebuilt form or rendered output to be requested.
Documentation links
$form['source_dependent']['source'] = [
'#type' => 'select',
'#title' => $this->t('Media source'),
'#default_value' => $source ? $source->getPluginId() : NULL,
'#options' => $options,
'#description' => $source_description,
'#required' => TRUE,
// Once the media type is created, its source plugin cannot be changed
// anymore.
'#disabled' => !$this->entity->isNew(),
];
(new Htmx())->post($formUrl)
->select('#source-dependent')
->target('#source-dependent')
->swap('outerHTML')
->applyTo($form['source_dependent']['source']);Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.