You are here

public function SubscriptionsBlockForm::validateForm in Simplenews 3.x

Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level validation handler, otherwise an exception will be thrown.

Overrides ContentEntityForm::validateForm

File

src/Form/SubscriptionsBlockForm.php, line 92

Class

SubscriptionsBlockForm
Add subscriptions for authenticated user or new subscriber.

Namespace

Drupal\simplenews\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $mail = $form_state
    ->getValue([
    'mail',
    0,
    'value',
  ]);
  if ($this->entity
    ->isNew() && ($subscriber = Subscriber::loadByMail($mail))) {
    $this
      ->setEntity($subscriber);
  }
  parent::validateForm($form, $form_state);

  // If the newsletter checkboxes are available, at least one must be checked.
  if (!$this
    ->getSubscriptionWidget($form_state)
    ->isHidden() && !count($form_state
    ->getValue('subscriptions'))) {
    $form_state
      ->setErrorByName('subscriptions', $this
      ->t('You must select at least one newsletter.'));
  }
  $mail = $form_state
    ->getValue([
    'mail',
    0,
    'value',
  ]);

  // Cannot subscribe blocked users.
  if (($user = user_load_by_mail($mail)) && $user
    ->isBlocked()) {
    $message = $this
      ->t('The email address %mail belongs to a blocked user.', [
      '%mail' => $mail,
    ]);
    $form_state
      ->setErrorByName('mail', $message);
  }
}