PrependCommand

Last updated on
18 December 2025

Ajax API

PrependCommand

$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['prepend'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'prepend-item'],
];

if ($selected_value = $form_state->getValue('selector')) {
  $form['prepend']['render'] = [
    '#type' => 'html_tag',
    '#tag' => 'div',
    '#value' => $options[$selected_value],
  ];
}

// With this callback.  The form prepends the children of $form['prepend']['render'] to the existing $form['prepend'] wrapper.

/**
 * Ajax callback triggered by the type provider select element.
 */
public function ajaxHandlerData(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new PrependCommand('#prepend-item', $form['prepend']['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. 

$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['prepend'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'prepend-item'],
];

if ($selected_value = $form_state->getValue('selector')) {
  $form['prepend']['render'] = [
    '#type' => 'html_tag',
    '#tag' => 'div',
    '#value' => $options[$selected_value],
  ];
}

(new Htmx())->post($formUrl)
  ->select('#prepend-item div')
  ->target('#prepend-item')
  ->swap('afterbegin')
  ->applyTo($form['selector']);

Help improve this page

Page status: No known problems

You can: