You are here

public function SubscriberMassUnsubscribeForm::submitForm in Simplenews 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/SubscriberMassUnsubscribeForm.php \Drupal\simplenews\Form\SubscriberMassUnsubscribeForm::submitForm()
  2. 8 src/Form/SubscriberMassUnsubscribeForm.php \Drupal\simplenews\Form\SubscriberMassUnsubscribeForm::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/SubscriberMassUnsubscribeForm.php, line 94

Class

SubscriberMassUnsubscribeForm
Do a mass subscription for a list of email addresses.

Namespace

Drupal\simplenews\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $removed = [];
  $invalid = [];
  $checked_lists = array_keys(array_filter($form_state
    ->getValue('newsletters')));
  $emails = preg_split("/[\\s,]+/", $form_state
    ->getValue('emails'));
  foreach ($emails as $email) {
    $email = trim($email);
    if ($this->emailValidator
      ->isValid($email)) {
      foreach ($checked_lists as $newsletter_id) {
        $this->subscriptionManager
          ->unsubscribe($email, $newsletter_id, FALSE, 'mass unsubscribe');
        $removed[] = $email;
      }
    }
    else {
      $invalid[] = $email;
    }
  }
  if ($removed) {
    $removed = implode(", ", $removed);
    $this
      ->messenger()
      ->addMessage($this
      ->t('The following addresses were unsubscribed: %removed.', [
      '%removed' => $removed,
    ]));
    $newsletters = simplenews_newsletter_get_all();
    $list_names = [];
    foreach ($checked_lists as $newsletter_id) {
      $list_names[] = $newsletters[$newsletter_id]
        ->label();
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('The addresses were unsubscribed from the following newsletters: %newsletters.', [
      '%newsletters' => implode(', ', $list_names),
    ]));
  }
  else {
    $this
      ->messenger()
      ->addMessage($this
      ->t('No addresses were removed.'));
  }
  if ($invalid) {
    $invalid = implode(", ", $invalid);
    $this
      ->messenger()
      ->addError($this
      ->t('The following addresses were invalid: %invalid.', [
      '%invalid' => $invalid,
    ]));
  }

  // Return to the parent page.
  $form_state
    ->setRedirect('entity.simplenews_subscriber.collection');
}