You are here

class MailchimpListsSubscribeForm in Mailchimp 8

Same name and namespace in other branches
  1. 2.x modules/mailchimp_lists/src/Form/MailchimpListsSubscribeForm.php \Drupal\mailchimp_lists\Form\MailchimpListsSubscribeForm

Subscribe to a Mailchimp list/audience.

Hierarchy

Expanded class hierarchy of MailchimpListsSubscribeForm

1 file declares its use of MailchimpListsSubscribeForm
MailchimpListsFieldSubscribeFormatter.php in modules/mailchimp_lists/src/Plugin/Field/FieldFormatter/MailchimpListsFieldSubscribeFormatter.php

File

modules/mailchimp_lists/src/Form/MailchimpListsSubscribeForm.php, line 13

Namespace

Drupal\mailchimp_lists\Form
View source
class MailchimpListsSubscribeForm extends FormBase {
  use StringTranslationTrait;

  /**
   * The ID for this form.
   *
   * Set as class property so it can be overwritten as needed.
   *
   * @var string
   */
  private $formId = 'mailchimp_lists_subscribe';

  /**
   * The MailchimpListsSubscription field instance used to build this form.
   *
   * @var \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription
   */
  private $fieldInstance;

  /**
   * A reference to the field formatter used to build this form.
   *
   * Used to get field configuration.
   *
   * @var \Drupal\mailchimp_lists\Plugin\Field\FieldFormatter\MailchimpListsFieldSubscribeFormatter
   */
  private $fieldFormatter;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return $this->formId;
  }

  /**
   * Sets the form ID.
   *
   * @param string $formId
   *   The form ID.
   */
  public function setFormId($formId) {
    $this->formId = $formId;
  }

  /**
   * Sets the field instance service.
   *
   * @param \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription $fieldInstance
   *   The field instance service.
   */
  public function setFieldInstance(MailchimpListsSubscription $fieldInstance) {
    $this->fieldInstance = $fieldInstance;
  }

  /**
   * Sets the field formatter service.
   *
   * @param \Drupal\mailchimp_lists\Plugin\Field\FieldFormatter\MailchimpListsFieldSubscribeFormatter $fieldFormatter
   *   The field formatter service.
   */
  public function setFieldFormatter(MailchimpListsFieldSubscribeFormatter $fieldFormatter) {
    $this->fieldFormatter = $fieldFormatter;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'mailchimp_lists.subscribe',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];
    $field_settings = $this->fieldInstance
      ->getFieldDefinition()
      ->getSettings();
    $field_formatter_settings = $this->fieldFormatter
      ->getSettings();
    $mc_list = mailchimp_get_list($field_settings['mc_list_id']);
    $email = mailchimp_lists_load_email($this->fieldInstance, $this->fieldInstance
      ->getEntity());
    if (!$email) {
      return [];
    }
    $field_name = $this->fieldInstance
      ->getFieldDefinition()
      ->getName();

    // Determine if a user is subscribed to the list.
    $is_subscribed = mailchimp_is_subscribed($mc_list['id'], $email);
    $wrapper_key = 'mailchimp_' . $field_name;
    $form['wrapper_key'] = [
      '#type' => 'hidden',
      '#default_value' => $wrapper_key,
    ];
    $form[$wrapper_key] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#description' => $this->fieldInstance
        ->getFieldDefinition()
        ->getDescription(),
      '#attributes' => [
        'class' => [
          'mailchimp-newsletter-wrapper',
          'mailchimp-newsletter-' . $field_name,
        ],
      ],
    ];

    // Add title and description to lists for anonymous users or if requested:
    $form[$wrapper_key]['subscribe'] = [
      '#type' => 'checkbox',
      '#title' => 'Subscribe',
      '#disabled' => $this->fieldInstance
        ->getFieldDefinition()
        ->isRequired(),
      '#required' => $this->fieldInstance
        ->getFieldDefinition()
        ->isRequired(),
      '#default_value' => $this->fieldInstance
        ->getFieldDefinition()
        ->isRequired() || $is_subscribed,
    ];

    // Present interest groups:
    if ($field_settings['show_interest_groups'] && $field_formatter_settings['show_interest_groups']) {

      // Perform test in case error comes back from MCAPI when getting groups:
      if (is_array($mc_list['intgroups'])) {
        $form[$wrapper_key]['interest_groups'] = [
          '#type' => 'fieldset',
          '#title' => isset($field_settings['interest_groups_label']) ? $field_settings['interest_groups_label'] : $this
            ->t('Interest Groups'),
          '#weight' => 100,
          '#states' => [
            'invisible' => [
              ':input[name="' . $wrapper_key . '[subscribe]"]' => [
                'checked' => FALSE,
              ],
            ],
          ],
        ];
        $groups_default = $this->fieldInstance
          ->getInterestGroups();
        if ($groups_default == NULL) {
          $groups_default = [];
        }
        $form[$wrapper_key]['interest_groups'] += mailchimp_interest_groups_form_elements($mc_list, $groups_default, $email);
      }
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $wrapper_key = $form_state
      ->getValue('wrapper_key');
    $choices = $form_state
      ->getValue($wrapper_key);
    mailchimp_lists_process_subscribe_form_choices($choices, $this->fieldInstance, $this->fieldInstance
      ->getEntity());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MailchimpListsSubscribeForm::$fieldFormatter private property A reference to the field formatter used to build this form.
MailchimpListsSubscribeForm::$fieldInstance private property The MailchimpListsSubscription field instance used to build this form.
MailchimpListsSubscribeForm::$formId private property The ID for this form.
MailchimpListsSubscribeForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MailchimpListsSubscribeForm::getEditableConfigNames protected function
MailchimpListsSubscribeForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MailchimpListsSubscribeForm::setFieldFormatter public function Sets the field formatter service.
MailchimpListsSubscribeForm::setFieldInstance public function Sets the field instance service.
MailchimpListsSubscribeForm::setFormId public function Sets the form ID.
MailchimpListsSubscribeForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.