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.
13 class FormTestRebuildPreserveValuesForm extends FormBase {
18 public function getFormId() {
19 return 'form_test_form_rebuild_preserve_values_form';
25 public function buildForm(array $form, FormStateInterface $form_state) {
26 // Start the form with two checkboxes, to test different defaults, and a
27 // textfield, to test more than one element type.
29 'checkbox_1_default_off' => [
30 '#type' => 'checkbox',
31 '#title' => t('This checkbox defaults to unchecked'),
32 '#default_value' => FALSE,
34 'checkbox_1_default_on' => [
35 '#type' => 'checkbox',
36 '#title' => t('This checkbox defaults to checked'),
37 '#default_value' => TRUE,
40 '#type' => 'textfield',
41 '#title' => t('This textfield has a non-empty default value.'),
42 '#default_value' => 'DEFAULT 1',
45 // Provide an 'add more' button that rebuilds the form with an additional two
46 // checkboxes and a textfield. The test is to make sure that the rebuild
47 // triggered by this button preserves the user input values for the initial
48 // elements and initializes the new elements with the correct default values.
49 if (!$form_state->has('add_more')) {
52 '#value' => 'Add more',
53 '#submit' => ['::addMoreSubmitForm'],
58 'checkbox_2_default_off' => [
59 '#type' => 'checkbox',
60 '#title' => t('This checkbox defaults to unchecked'),
61 '#default_value' => FALSE,
63 'checkbox_2_default_on' => [
64 '#type' => 'checkbox',
65 '#title' => t('This checkbox defaults to checked'),
66 '#default_value' => TRUE,
69 '#type' => 'textfield',
70 '#title' => t('This textfield has a non-empty default value.'),
71 '#default_value' => 'DEFAULT 2',
75 // A submit button that finishes the form workflow (does not rebuild).
86 public function addMoreSubmitForm(array &$form, FormStateInterface $form_state) {
87 // Rebuild, to test preservation of input values.
88 $form_state->set('add_more', TRUE);
89 $form_state->setRebuild();
95 public function submitForm(array &$form, FormStateInterface $form_state) {
96 // Finish the workflow. Do not rebuild.
97 drupal_set_message(t('Form values: %values', ['%values' => var_export($form_state->getValues(), TRUE)]));