3 namespace Drupal\form_test\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Form builder for testing preservation of values during a rebuild.
11 class FormTestRebuildPreserveValuesForm extends FormBase {
16 public function getFormId() {
17 return 'form_test_form_rebuild_preserve_values_form';
23 public function buildForm(array $form, FormStateInterface $form_state) {
24 // Start the form with two checkboxes, to test different defaults, and a
25 // textfield, to test more than one element type.
27 'checkbox_1_default_off' => [
28 '#type' => 'checkbox',
29 '#title' => t('This checkbox defaults to unchecked'),
30 '#default_value' => FALSE,
32 'checkbox_1_default_on' => [
33 '#type' => 'checkbox',
34 '#title' => t('This checkbox defaults to checked'),
35 '#default_value' => TRUE,
38 '#type' => 'textfield',
39 '#title' => t('This textfield has a non-empty default value.'),
40 '#default_value' => 'DEFAULT 1',
43 // Provide an 'add more' button that rebuilds the form with an additional two
44 // checkboxes and a textfield. The test is to make sure that the rebuild
45 // triggered by this button preserves the user input values for the initial
46 // elements and initializes the new elements with the correct default values.
47 if (!$form_state->has('add_more')) {
50 '#value' => 'Add more',
51 '#submit' => ['::addMoreSubmitForm'],
56 'checkbox_2_default_off' => [
57 '#type' => 'checkbox',
58 '#title' => t('This checkbox defaults to unchecked'),
59 '#default_value' => FALSE,
61 'checkbox_2_default_on' => [
62 '#type' => 'checkbox',
63 '#title' => t('This checkbox defaults to checked'),
64 '#default_value' => TRUE,
67 '#type' => 'textfield',
68 '#title' => t('This textfield has a non-empty default value.'),
69 '#default_value' => 'DEFAULT 2',
73 // A submit button that finishes the form workflow (does not rebuild).
84 public function addMoreSubmitForm(array &$form, FormStateInterface $form_state) {
85 // Rebuild, to test preservation of input values.
86 $form_state->set('add_more', TRUE);
87 $form_state->setRebuild();
93 public function submitForm(array &$form, FormStateInterface $form_state) {
94 // Finish the workflow. Do not rebuild.
95 drupal_set_message(t('Form values: %values', ['%values' => var_export($form_state->getValues(), TRUE)]));