Score:0

Check in buildForm method of custom form class if the form was submitted

cn flag

I have created a large form with a class extending FormBase. Many of the elements rendered within the form are only necessary for the user to see - there are not so many really relevant fields in the form but all this data gathering and rendering takes time.

When a form is submitted the buildForm() method is called first and after that the submitForm() method. Then the buildForm() method gets called again which then is really used to render the form for the user.

I now wonder if it is possible to check within the buildForm() method if it is called during the first run before submitForm() or if it is used during the second run to actually render it.

FormState->isSubmitted() does not do the trick - this is false on buildForm() on the first run.

4uk4 avatar
cn flag
Check $form_state->getUserInput(). See https://drupal.stackexchange.com/questions/288795/how-to-determine-if-loading-a-form-or-submitting-a-form-in-hook-form-alter
Tobias Krause avatar
cn flag
Thank you so much!
Score:1
cn flag

The form is submitted when there is user input:

public function buildForm(array $form, FormStateInterface $form_state) {
  if ($form_state->getUserInput()) {
    // The form was submitted. 
    // Build a minimal $form containing only the necessary form elements
    // to submit the user input.
  }
}

BTW, buildForm() can be called again, in the same request, if a submit handler causes a form rebuild or in Ajax forms. The user input is processed, $form_state->getValues() and $form_state->getTriggeringElement() are filled with data and can then be used to build a different version of the form.

If the form is not rebuilding it redirects by default to the same URL and builds a new empty form. If this takes too long and the user probably doesn't want to submit the form again, you can change this default behavior and set a different URL.

For example, redirect to the homepage and set a message:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->messenger()->addStatus($this->t('The form has been submitted.'));
  $form_state->setRedirect('<front>');
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.