Same filename and directory in other branches
- 8.9.x core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
- 9 core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
Namespace
Drupal\form_test\Form
File
core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
View source
<?php
namespace Drupal\form_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class FormTestRebuildPreserveValuesForm extends FormBase {
public function getFormId() {
return 'form_test_form_rebuild_preserve_values_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form = [
'checkbox_1_default_off' => [
'#type' => 'checkbox',
'#title' => t('This checkbox defaults to unchecked'),
'#default_value' => FALSE,
],
'checkbox_1_default_on' => [
'#type' => 'checkbox',
'#title' => t('This checkbox defaults to checked'),
'#default_value' => TRUE,
],
'text_1' => [
'#type' => 'textfield',
'#title' => t('This textfield has a non-empty default value.'),
'#default_value' => 'DEFAULT 1',
],
];
if (!$form_state
->has('add_more')) {
$form['add_more'] = [
'#type' => 'submit',
'#value' => 'Add more',
'#submit' => [
'::addMoreSubmitForm',
],
];
}
else {
$form += [
'checkbox_2_default_off' => [
'#type' => 'checkbox',
'#title' => t('This checkbox defaults to unchecked'),
'#default_value' => FALSE,
],
'checkbox_2_default_on' => [
'#type' => 'checkbox',
'#title' => t('This checkbox defaults to checked'),
'#default_value' => TRUE,
],
'text_2' => [
'#type' => 'textfield',
'#title' => t('This textfield has a non-empty default value.'),
'#default_value' => 'DEFAULT 2',
],
];
}
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Submit',
];
return $form;
}
public function addMoreSubmitForm(array &$form, FormStateInterface $form_state) {
$form_state
->set('add_more', TRUE);
$form_state
->setRebuild();
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this
->messenger()
->addStatus($this
->t('Form values: %values', [
'%values' => var_export($form_state
->getValues(), TRUE),
]));
}
}
Classes