You are here

public function DynamicFormSections::submitForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/ajax_example/src/Form/DynamicFormSections.php \Drupal\ajax_example\Form\DynamicFormSections::submitForm()

Final submit handler.

Reports what values were finally set.

Overrides FormInterface::submitForm

File

ajax_example/src/Form/DynamicFormSections.php, line 174

Class

DynamicFormSections
Dynamically-enabled form with graceful no-JS degradation.

Namespace

Drupal\ajax_example\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $messenger = $this
    ->messenger();

  // This is only executed when a button is pressed, not when the AJAXfield
  // select is changed.
  // Now handle the case of the next, previous, and submit buttons.
  // Only submit will result in actual submission, all others rebuild.
  if ($form_state
    ->getValue('question_type_submit') == 'Choose') {
    $form_state
      ->setValue('question_type_select', $form_state
      ->getUserInput()['question_type_select']);
    $form_state
      ->setRebuild();
  }
  if ($form_state
    ->getValue('submit') == 'Submit your answer') {
    $form_state
      ->setRebuild(FALSE);
    $answer = $form_state
      ->getValue('question');

    // Special handling for the checkbox.
    if ($answer == 1 && $form['questions_fieldset']['question']['#type'] == 'checkbox') {
      $answer = $form['questions_fieldset']['question']['#title'];
    }
    if ($answer == $this
      ->t('George Washington')) {
      $messenger
        ->addMessage($this
        ->t('You got the right answer: @answer', [
        '@answer' => $answer,
      ]));
    }
    else {
      $messenger
        ->addMessage($this
        ->t('Sorry, your answer (@answer) is wrong', [
        '@answer' => $answer,
      ]));
    }
    return;
  }

  // Sets the form to be rebuilt after processing.
  $form_state
    ->setRebuild();
}