You are here

public function MailchimpSignupPageForm::validateForm in Mailchimp 8

Same name and namespace in other branches
  1. 2.x modules/mailchimp_signup/src/Form/MailchimpSignupPageForm.php \Drupal\mailchimp_signup\Form\MailchimpSignupPageForm::validateForm()

Form validation 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 FormBase::validateForm

File

modules/mailchimp_signup/src/Form/MailchimpSignupPageForm.php, line 273

Class

MailchimpSignupPageForm
Subscribe to a Mailchimp list/audience.

Namespace

Drupal\mailchimp_signup\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $build_info = $form_state
    ->getBuildInfo();
  $signup = $build_info['callback_object']->signup;

  // For forms that allow subscribing to multiple lists/audiences
  // ensure at least one list/audience has been selected.
  // Get the enabled lists/audiences for this form.
  $enabled_lists = array_filter($signup->mc_lists);
  if (count($enabled_lists) > 1) {

    // Filter the selected lists out of the form values.
    $selected_lists = array_filter($form_state
      ->getValue('mailchimp_lists'), function ($list) {
      return $list['subscribe'];
    });

    // If a list has been selected, validation passes.
    if (!empty($selected_lists)) {
      return;
    }
    $form_state
      ->setErrorByName('mailchimp_lists', $this
      ->t("Please select at least one audience to subscribe to."));
  }
}