Advertising sustains the DA. Ads are hidden for members. Join today
On this page
Ajax API to HTMX
- Overview
- AddCssCommand
- AddJsCommand
- AfterCommand
- AlertCommand
- AnnounceCommand
- AppendCommand
- BeforeCommand
- ChangedCommand
- CloseDialogCommand
- CloseModalDialogCommand
- CssCommand
- DataCommand
- FocusFirstCommand
- HtmlCommand
- InsertCommand
- InvokeCommand
- MessageCommand
- OpenDialogCommand
- OpenModalDialogCommand
- OpenOffCanvasDialogCommand
- PrependCommand
- RedirectCommand
- RemoveCommand
- ReplaceCommand
- RestripeCommand
- SetDialogOptionCommand
- TabledragWarningCommand
- UpdateSelectionCommand
AppendCommand
Last updated on
18 December 2025
Ajax API
AppendCommand
$options = [
'red' => $this->t('Red'),
'green' => $this->t('Green'),
'blue' => $this->t('Blue'),
'yellow' => $this->t('Yellow'),
];
$form['selector'] = [
'#type' => 'select',
'#title' => $this->t('Choose an item'),
'#empty_option' => $this->t('- Choose -'),
'#options' => $options,
'#ajax' => ['callback' => '::ajaxHandlerData'],
'#required' => TRUE,
];
$form['append'] = [
'#type' => 'container',
'#attributes' => ['id' => 'append-item'],
];
if ($selected_value = $form_state->getValue('selector')) {
$form['append']['render'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $options[$selected_value],
];
}
// With this callback. The form appends the children of $form['append']['render'] to the existing $form['append'] wrapper.
/**
* Ajax callback triggered by the type provider select element.
*/
public function ajaxHandlerData(array $form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new AppendCommand('#append-item', $form['append']['render']));
return $response;
}
HTMX
In this case 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
$options = [
'red' => $this->t('Red'),
'green' => $this->t('Green'),
'blue' => $this->t('Blue'),
'yellow' => $this->t('Yellow'),
];
$form['selector'] = [
'#type' => 'select',
'#title' => $this->t('Choose an item'),
'#empty_option' => $this->t('- Choose -'),
'#options' => $options,
'#required' => TRUE,
];
$form['append'] = [
'#type' => 'container',
'#attributes' => ['id' => 'append-item'],
];
if ($selected_value = $form_state->getValue('selector')) {
$form['append']['render'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $options[$selected_value],
];
}
(new Htmx())->post($formUrl)
->select('#append-item div')
->target('#append-item')
->swap('beforeend')
->applyTo($form['selector']);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