You are here

public function MailchimpCampaignForm::validateForm in Mailchimp 8

Same name and namespace in other branches
  1. 2.x modules/mailchimp_campaign/src/Form/MailchimpCampaignForm.php \Drupal\mailchimp_campaign\Form\MailchimpCampaignForm::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

modules/mailchimp_campaign/src/Form/MailchimpCampaignForm.php, line 352

Class

MailchimpCampaignForm
Form controller for the MailchimpCampaign entity edit form.

Namespace

Drupal\mailchimp_campaign\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  if ($form_state
    ->getValue('op') == $form['actions']['submit']['#value']) {

    // Try to save form to campaign in MailChimp.
    $values = $form_state
      ->getValues();
    $recipients = (object) [
      'list_id' => $values['list_id'],
    ];
    if (isset($values['list_segment_id']) && !empty($values['list_segment_id'])) {
      $recipients->segment_opts = (object) [
        'saved_segment_id' => (int) $values['list_segment_id'],
      ];
    }
    $settings = (object) [
      'subject_line' => $values['subject'],
      'title' => $values['title'],
      'from_name' => $values['from_name'],
      'reply_to' => $values['from_email'],
      'preview_text' => $values['preview_text'],
    ];
    $template_content = $this
      ->parseTemplateContent($form_state
      ->getValue('content') ?: []);

    /* @var \Drupal\mailchimp_campaign\Entity\MailchimpCampaign $campaign */
    $campaign = $this
      ->getEntity();
    $campaign_id = mailchimp_campaign_save_campaign($template_content, $recipients, $settings, $values['template_id'], $campaign
      ->getMcCampaignId());

    // In case of an error by MailChimp, the campaign_id is not set.
    // E.g. when the email address entered is not considered valid.
    // This would result in a SQL exception that leaves the user puzzled.
    // It's better to inform the user and abort the save operation.
    if (empty($campaign_id)) {
      $form_state
        ->setErrorByName('submit', t('An error occured while saving this campaign to MailChimp service.'));
    }
    else {

      // Save campaign id to entity
      $campaign
        ->setMcCampaignId($campaign_id);
      $campaign
        ->setTemplate($template_content);
    }
  }
}