You are here

public function SubscriptionsFormBase::validateForm in Simplenews 8.2

Same name and namespace in other branches
  1. 8 src/Form/SubscriptionsFormBase.php \Drupal\simplenews\Form\SubscriptionsFormBase::validateForm()

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/SubscriptionsFormBase.php, line 214

Class

SubscriptionsFormBase
Entity form for Subscriber with common routines.

Namespace

Drupal\simplenews\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $mail = $form_state
    ->getValue([
    'mail',
    0,
    'value',
  ]);

  // Users should login to manage their subscriptions.
  if (\Drupal::currentUser()
    ->isAnonymous() && ($user = user_load_by_mail($mail))) {
    $message = $user
      ->isBlocked() ? $this
      ->t('The email address %mail belongs to a blocked user.', [
      '%mail' => $mail,
    ]) : $this
      ->t('There is an account registered for the e-mail address %mail. Please log in to manage your newsletter subscriptions.', [
      '%mail' => $mail,
    ]);
    $form_state
      ->setErrorByName('mail', $message);
  }

  // Unless the submit handler is 'update', if the newsletter checkboxes are
  // available, at least one must be checked.
  $update = in_array('::submitUpdate', $form_state
    ->getSubmitHandlers());
  if (!$update && !$this
    ->getSubscriptionWidget($form_state)
    ->isHidden() && !count($form_state
    ->getValue('subscriptions'))) {
    $form_state
      ->setErrorByName('subscriptions', $this
      ->t('You must select at least one newsletter.'));
  }
  parent::validateForm($form, $form_state);
}