Skip to content

Commit 15ffc62

Browse files
Mile23paul-m
Mile23
authored andcommitted
Issue #2942627 by Mile23, joachim: calls to form state setRebuild() and setCached() need to be explained
1 parent b5d3b31 commit 15ffc62

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

form_api_example/src/Form/AjaxAddMore.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ public function buildForm(array $form, FormStateInterface $form_state) {
7474
],
7575
];
7676
}
77-
$form_state->setCached(FALSE);
7877
$form['actions']['submit'] = [
7978
'#type' => 'submit',
8079
'#value' => $this->t('Submit'),
@@ -108,6 +107,9 @@ public function addOne(array &$form, FormStateInterface $form_state) {
108107
$name_field = $form_state->get('num_names');
109108
$add_button = $name_field + 1;
110109
$form_state->set('num_names', $add_button);
110+
// Since our buildForm() method relies on the value of 'num_names' to
111+
// generate 'name' form elements, we have to tell the form to rebuild. If we
112+
// don't do this, the form builder will not call buildForm().
111113
$form_state->setRebuild();
112114
}
113115

@@ -122,6 +124,9 @@ public function removeCallback(array &$form, FormStateInterface $form_state) {
122124
$remove_button = $name_field - 1;
123125
$form_state->set('num_names', $remove_button);
124126
}
127+
// Since our buildForm() method relies on the value of 'num_names' to
128+
// generate 'name' form elements, we have to tell the form to rebuild. If we
129+
// don't do this, the form builder will not call buildForm().
125130
$form_state->setRebuild();
126131
}
127132

form_api_example/src/Form/MultistepForm.php

+6
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,9 @@ public function fapiExampleMultistepFormNextSubmit(array &$form, FormStateInterf
129129
'birth_year' => $form_state->getValue('birth_year'),
130130
])
131131
->set('page_num', 2)
132+
// Since we have logic in our buildForm() method, we have to tell the form
133+
// builder to rebuild the form. Otherwise, even though we set 'page_num'
134+
// to 2, the AJAX-rendered form will still show page 1.
132135
->setRebuild(TRUE);
133136
}
134137

@@ -187,6 +190,9 @@ public function fapiExamplePageTwoBack(array &$form, FormStateInterface $form_st
187190
// Restore values for the first step.
188191
->setValues($form_state->get('page_values'))
189192
->set('page_num', 1)
193+
// Since we have logic in our buildForm() method, we have to tell the form
194+
// builder to rebuild the form. Otherwise, even though we set 'page_num'
195+
// to 1, the AJAX-rendered form will still show page 2.
190196
->setRebuild(TRUE);
191197
}
192198

0 commit comments

Comments
 (0)