You are here

public function SubscriberMassUnsubscribeForm::submitForm in Simplenews 8

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

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 = array();
  $invalid = array();
  $checked_lists = array_keys(array_filter($form_state
    ->getValue('newsletters')));

  /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */
  $subscription_manager = \Drupal::service('simplenews.subscription_manager');
  $emails = preg_split("/[\\s,]+/", $form_state
    ->getValue('emails'));
  foreach ($emails as $email) {
    $email = trim($email);
    if (valid_email_address($email)) {
      foreach ($checked_lists as $newsletter_id) {
        $subscription_manager
          ->unsubscribe($email, $newsletter_id, FALSE, 'mass unsubscribe');
        $removed[] = $email;
      }
    }
    else {
      $invalid[] = $email;
    }
  }
  if ($removed) {
    $removed = implode(", ", $removed);
    $this
      ->messenger()
      ->addMessage(t('The following addresses were unsubscribed: %removed.', array(
      '%removed' => $removed,
    )));
    $newsletters = simplenews_newsletter_get_all();
    $list_names = array();
    foreach ($checked_lists as $newsletter_id) {
      $list_names[] = $newsletters[$newsletter_id]
        ->label();
    }
    $this
      ->messenger()
      ->addMessage(t('The addresses were unsubscribed from the following newsletters: %newsletters.', array(
      '%newsletters' => implode(', ', $list_names),
    )));
  }
  else {
    $this
      ->messenger()
      ->addMessage(t('No addresses were removed.'));
  }
  if ($invalid) {
    $invalid = implode(", ", $invalid);
    $this
      ->messenger()
      ->addError(t('The following addresses were invalid: %invalid.', array(
      '%invalid' => $invalid,
    )));
  }

  // Return to the parent page.
  $form_state
    ->setRedirect('view.simplenews_subscribers.page_1');
}