You are here

class CampaignMonitorUserSubscriptionForm in Campaign Monitor 8

Subscribe to a campaignmonitor list.

Hierarchy

Expanded class hierarchy of CampaignMonitorUserSubscriptionForm

File

modules/campaignmonitor_user/src/Form/CampaignMonitorUserSubscriptionForm.php, line 14

Namespace

Drupal\campaignmonitor_user\Form
View source
class CampaignMonitorUserSubscriptionForm extends FormBase {

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

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

  /**
   *
   */
  public function setFormId($formId) {
    $this->formId = $formId;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $user = NULL) {

    // Get the e-mail address from the user object.
    // This is not working - url is always user 1.
    $account = User::load($user);
    $current_user = \Drupal::currentUser();
    $account = User::load($current_user
      ->id());
    $email = $account
      ->get('mail')
      ->getValue()[0]['value'];
    $config = \Drupal::config('campaignmonitor_user.settings');
    $form = [];
    $form['email'] = [
      '#type' => 'hidden',
      '#value' => $email,
    ];
    $form['name'] = [
      '#type' => 'hidden',
      '#value' => $account
        ->get('name')
        ->getValue()[0]['value'],
    ];
    $lists = campaignmonitor_get_lists();

    // Build options for the form selector.
    $options = [];
    $option_descriptions = [];
    $default = [];
    foreach ($lists as $list_id => $list) {

      // Check if the list is selected to be shown.
      $list_options = campaignmonitor_get_list_settings($list_id);
      if (campaignmonitor_is_list_enabled($list_id)) {
        $options[$list_id] = $list['name'];
        $defaults = campaignmonitor_get_list_settings($list_id);
        $option_descriptions[$list_id] = $defaults['display']['description'];

        // Check if the user is subscribed to the current list.
        $default[$list_id] = 0;
        if (campaignmonitor_is_subscribed($list_id, $email)) {
          $default[$list_id] = $list_id;
        }
      }
    }
    if (!empty($options)) {
      $form['subscription_text'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'subscription-text',
          ],
        ],
      ];
      $form['subscription_text']['text'] = [
        '#markup' => $config
          ->get('subscription_text'),
      ];
      $form['lists'] = [
        '#type' => 'checkboxes',
        '#title' => $config
          ->get('list_heading'),
        // '#description' => !empty($config['instructions']) ? t($config['instructions']) : t('Select the news lists
        //        that you want to subscribe to.'),.
        '#options' => $options,
        '#default_value' => $default,
        '#option_descriptions' => $option_descriptions,
        '#after_build' => [
          '\\Drupal\\campaignmonitor_user\\Form\\CampaignMonitorUserSubscriptionForm::_option_descriptions',
        ],
      ];
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => t('Update subscriptions'),
        '#attached' => [
          'library' => [
            'campaignmonitor_user/campaignmonitor_user.subscriptions',
          ],
        ],
      ];
    }
    else {
      drupal_set_message('There are no available lists to subscribe to at the moment.', 'warning');
    }
    return $form;
  }

  /**
   *
   */
  public static function _option_descriptions($element, &$form_state) {
    foreach (Element::children($element) as $key) {
      $element[$key]['#description'] = t('@description', [
        '@description' => $element['#option_descriptions'][$key],
      ]);
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $lists = campaignmonitor_get_lists();
    $values = $form_state
      ->getValues();
    $subscribed = FALSE;
    $config = $form_state
      ->getValue('config');
    $config = unserialize($config);

    // Loop through the lists.
    foreach ($values['lists'] as $list_id => $selected) {
      if ($selected !== 0) {

        // Maybe this is an unsubscribe.
        if (campaignmonitor_subscribe($list_id, $values['email'], $values['name'])) {
          drupal_set_message(t('You are now subscribed to the "@list" list.', [
            '@list' => html_entity_decode($lists[$list_id]['name']),
          ]), 'status');
          $subscribed = TRUE;
        }
        else {
          drupal_set_message(t('You were not subscribed to the list. Please try again later.'));
        }

        // Check if the user should be sent to an unsubscribe page.
        //          if (isset($lists_info[$list_id]['details']['UnsubscribePage']) && !empty($lists_info[$list_id]['details']['UnsubscribePage'])) {
        //            drupal_goto($lists_info[$list_id]['details']['UnsubscribePage']);
        //          }
        //          else {
        //            drupal_set_message(t('You are now removed from the "@list" list.', array('@list' => $lists_info[$list_id]['name'])), 'status');
        //          }.
      }
      else {
        campaignmonitor_unsubscribe($list_id, $values['email']);
      }
    }
    if ($subscribed) {
      drupal_set_message(t('Changes to your preferences will take a minute or two to show on the site.'));
    }

    // Return to user page
    // If we stay on the form it will display the old information.
    $url = Url::fromRoute('user.page');
    $form_state
      ->setRedirectUrl($url);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CampaignMonitorUserSubscriptionForm::$formId private property The ID for this form. Set as class property so it can be overwritten as needed.
CampaignMonitorUserSubscriptionForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
CampaignMonitorUserSubscriptionForm::getEditableConfigNames protected function
CampaignMonitorUserSubscriptionForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CampaignMonitorUserSubscriptionForm::setFormId public function
CampaignMonitorUserSubscriptionForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CampaignMonitorUserSubscriptionForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
CampaignMonitorUserSubscriptionForm::_option_descriptions public static function
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.
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.
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.