You are here

public function WebformInvitationForm::submitForm in Webform Invitation 2.0.x

Same name and namespace in other branches
  1. 8 src/Form/WebformInvitationForm.php \Drupal\webform_invitation\Form\WebformInvitationForm::submitForm()

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/WebformInvitationForm.php, line 59

Class

WebformInvitationForm
Enable or disable invitations for the current webform.

Namespace

Drupal\webform_invitation\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {

  /** @var \Drupal\webform\Entity\Webform $webform */
  $webform = $form_state
    ->getValue('webform');

  // Check if user wants to enable invitations.
  $enable = boolval($form_state
    ->getValue('enable'));
  $elements = $webform
    ->getElementsDecodedAndFlattened();

  // Check if current webform has enabled invitations.
  $enabled = isset($elements['webform_invitation_code']);

  // User wants invitations to be enabled.
  if ($enable) {

    // Only if invitations are not enabled.
    if (!$enabled) {

      // Create new code element.
      $element = [
        'webform_invitation_code' => [
          '#type' => 'textfield',
          '#title' => $this
            ->t('Invitation Code')
            ->render(),
          '#default_value' => '[current-page:query:code:clear]',
          '#description' => $this
            ->t('Enter your personal invitation code (only applies if the field is not populated yet).')
            ->render(),
          '#maxlength' => 64,
          '#required' => TRUE,
        ],
      ];

      // Prepend code element before others.
      $elements = $element + $elements;

      // Save changed elements into webform.
      $webform
        ->setElements($elements);
      $webform
        ->save();
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('Invitation mode has been activated. You should now <a href="@link">create some invitation codes</a>.', [
      '@link' => Url::fromRoute('entity.webform.invitation_generate', [
        'webform' => $webform
          ->id(),
      ])
        ->toString(),
    ]));
  }
  else {

    // Only if invitations are enabled.
    if ($enabled) {

      // Delete code element from webform.
      $webform
        ->deleteElement('webform_invitation_code');
      $webform
        ->save();
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('Invitation mode has been disabled.'));
  }
}