You are here

public function SubscribeForm::validateForm in SendinBlue 8

Same name and namespace in other branches
  1. 8.2 src/Form/SubscribeForm.php \Drupal\sendinblue\Form\SubscribeForm::validateForm()

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

File

src/Form/SubscribeForm.php, line 189

Class

SubscribeForm
Subscribe form to signup SendinBlue newsletter.

Namespace

Drupal\sendinblue\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $signup = $this->entityTypeManager
    ->getStorage(SendinblueManager::SENDINBLUE_SIGNUP_ENTITY)
    ->load($this->signupIp);
  $settings = !$signup->settings
    ->first() ? [] : $signup->settings
    ->first()
    ->getValue();
  $email = $form_state
    ->getValue([
    'fields',
    'EMAIL',
  ]);
  $list_id = $settings['subscription']['settings']['list'];
  if (!$this->emailValidator
    ->isValid($email)) {
    $form_state
      ->setErrorByName('email', $settings['subscription']['messages']['invalid']);
    return;
  }
  $response = $this->sendinblueManager
    ->validationEmail($email, $list_id);
  if ($response['code'] === 'invalid') {
    $form_state
      ->setErrorByName('email', $settings['subscription']['messages']['invalid']);
    return;
  }
  if ($response['code'] === 'already_exist') {
    $form_state
      ->setErrorByName('email', $settings['subscription']['messages']['existing']);
    return;
  }
  $list_ids = $response['listid'];
  $list_ids[] = $list_id;
  $info = [];
  $attributes = $this->sendinblueManager
    ->getAttributeLists();
  foreach ($attributes as $attribute) {
    $field_attribute_name = $form_state
      ->getValue([
      'fields',
      $attribute
        ->getName(),
    ]);
    if (isset($field_attribute_name)) {
      $info[$attribute
        ->getName()] = $form_state
        ->getValue([
        'fields',
        $attribute
          ->getName(),
      ]);
    }
  }
  $this->sendinblueManager
    ->subscribeUser($email, $info, $list_ids);

  // Store db.
  $data = $this->sendinblueManager
    ->getSubscriberByEmail($email);
  if ($data == FALSE) {
    $data = [
      'email' => $email,
      'info' => serialize($info),
      'code' => uniqid('', TRUE),
      'is_active' => 1,
    ];
    $this->sendinblueManager
      ->addSubscriberTable($data);
  }
}