function HtmxTestForm::buildForm
Form constructor.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
array The form structure.
Overrides FormInterface::buildForm
File
-
core/
modules/ system/ tests/ modules/ test_htmx/ src/ Form/ HtmxTestForm.php, line 27
Class
- HtmxTestForm
- A small form used to test HTMX dynamic forms.
Namespace
Drupal\test_htmx\FormCode
public function buildForm(array $form, FormStateInterface $form_state, ?string $type = NULL, ?string $selected = NULL) {
$type = $type ?? '';
$selected = $selected ?? '';
$formUrl = Url::fromRoute('<current>');
$form['type'] = [
'#type' => 'select',
'#title' => 'Type',
'#empty_value' => '',
'#options' => [
'a' => 'A',
'b' => 'B',
],
'#default_value' => $type,
];
(new Htmx())->post($formUrl)
->swap('none')
->swapOob('true')
->applyTo($form['type']);
$defaultType = $form_state->getValue('type', $type);
$form['selected'] = [
'#type' => 'select',
'#title' => 'Selected',
'#options' => $this->buildDependentOptions($defaultType),
'#empty_value' => '',
'#default_value' => $selected,
];
(new Htmx())->post($formUrl)
->swap('none')
->swapOob('true')
->applyTo($form['selected']);
$form['data'] = [
'#title' => 'Values',
'#type' => 'item',
'#markup' => '',
];
(new Htmx())->swapOob(TRUE)
->applyTo($form['data'], '#wrapper_attributes');
$push = FALSE;
if ($this->getTriggerElement($form_state) === 'type') {
$form['data']['#markup'] = '';
$push = Url::fromRoute('test_htmx.form_builder_test');
}
elseif ($this->getTriggerElement($form_state) === 'selected') {
// A value is selected.
$defaultSelection = $form_state->getValue('selected', $selected);
// Also update the browser URL.
$push = Url::fromRoute('test_htmx.form_builder_test', [
'type' => $defaultType,
'selected' => $defaultSelection,
]);
if ($defaultType && $defaultSelection) {
$form['data']['#markup'] = "Data is {$defaultType}:{$defaultSelection}";
}
}
elseif ($type && $selected) {
$form['data']['#markup'] = "Data is {$type}:{$selected}";
}
if ($push) {
$htmxPost = (new Htmx())->post($push)
->pushUrlHeader($push);
$htmxPost->applyTo($form['type']);
$htmxPost->applyTo($form['selected']);
}
return $form;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.