You are here

class CampaignMonitorIcsForm in Campaign Monitor 8

Subscribe to a campaignmonitor list.

Hierarchy

Expanded class hierarchy of CampaignMonitorIcsForm

File

modules/campaignmonitor_ics/src/Form/CampaignMonitorIcsForm.php, line 13

Namespace

Drupal\campaignmonitor_ics\Form
View source
class CampaignMonitorIcsForm extends FormBase {

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

  /**
   * The campaignmonitorListsSubscription field instance used to build this form.
   *
   * @var campaignmonitorListsSubscription
   */
  private $fieldInstance;

  /**
   * A reference to the field formatter used to build this form.
   * Used to get field configuration.
   *
   * @var campaignmonitorListsFieldSubscribeFormatter
   */
  private $fieldFormatter;

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $config = []) {

    // Try to get the e-mail address from the user object.
    if (\Drupal::currentUser()
      ->id() != 0) {
      $account = User::load(\Drupal::currentUser()
        ->id());
      $email = $account
        ->get('mail')
        ->getValue()[0]['value'];
    }
    $form['email'] = [
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
      '#maxlength' => 200,
      '#default_value' => isset($email) ? $email : '',
    ];
    switch ($config['list']) {
      case 'single':
        $form += $this
          ->singleSubscribeForm($form, $form_state, $config);
        $this
          ->setFormID($this->formId . '_single');
        break;
      default:
        $form += $this
          ->userSelectSubscribeForm($form, $form_state, $config);
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Subscribe'),
    ];
    $form['config'] = [
      '#type' => 'hidden',
      '#value' => serialize($config),
    ];
    return $form;
  }

  /**
   *
   */
  protected function singleSubscribeForm(array $form, FormStateInterface $form_state, $config = []) {
    $form = [];
    $list_id = $config['list_id'];
    $list = campaignmonitor_get_extended_list_settings($list_id);
    $list_options = campaignmonitor_get_list_settings($list_id);

    // Set options for the form.
    $form = [
      '#tree' => TRUE,
      '#attributes' => [
        'class' => [
          'campaignmonitor-subscribe-form',
          'campaignmonitor-subscribe-form-' . str_replace(' ', '-', strtolower($list['name'])),
        ],
      ],
    ];
    $text = str_replace('@name', $list['name'], $config['list_id_text']);
    $form['selection'] = [
      '#markup' => $text,
    ];

    // Should the name field be displayed for this user.
    if (isset($list_options['display']['name']) && $list_options['display']['name']) {

      // Token replace if the token module is present.
      if (isset($list_options['tokens']['name']) && \Drupal::moduleHandler()
        ->moduleExists('token') && $user->uid != 0) {
        $name = \Drupal::token()
          ->replace($list_options['tokens']['name'], [], [
          'clear' => TRUE,
        ]);
      }

      // Check if the user is subscribed and get name from Campaign Monitor.
      if (!empty($email) && $cm
        ->isSubscribed($list_id, $email)) {

        // If subscribed, get her/his name from Campaign Monitor.
        $subscriber = $cm
          ->getSubscriber($list_id, $email);
        $name = isset($subscriber['Name']) ? $subscriber['Name'] : $name;
      }
      $form['name'] = [
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#required' => TRUE,
        '#maxlength' => 200,
        '#default_value' => isset($name) ? $name : '',
      ];
    }
    if (isset($list['CustomFields'])) {
      foreach ($list['CustomFields'] as $key => $field) {

        // Form API can't handle keys with [] in all cases.
        $form_key = str_replace([
          '[',
          ']',
        ], '', $key);

        // Check if field should be displayed.
        if (isset($list_options['CustomFields']) && !$list_options['CustomFields']['selected'][$form_key]) {

          // Field is not selected, so continue.
          continue;
        }

        // Token replace default value, if the token module is present.
        $token = '';
        if (\Drupal::moduleHandler()
          ->moduleExists('token') && isset($list_options['tokens'][$form_key])) {
          $token = \Drupal::token()
            ->replace($list_options['tokens'][$form_key]);
        }
        switch ($field['DataType']) {
          case 'Text':
            $form['CustomFields'][$form_key] = [
              '#type' => 'textfield',
              '#title' => SafeMarkup::checkPlain($field['FieldName']),
              '#maxlength' => 200,
              '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
            ];
            break;
          case 'MultiSelectOne':
            $options = [];
            foreach ($field['FieldOptions'] as $option) {
              $options[$option] = $option;
            }
            $form['CustomFields'][$form_key] = [
              '#type' => 'select',
              '#title' => SafeMarkup::checkPlain($field['FieldName']),
              '#options' => $options,
              '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
            ];
            break;
          case 'MultiSelectMany':
            $options = [];
            foreach ($field['FieldOptions'] as $option) {
              $options[$option] = $option;
            }

            // If one value was selected, default is a string else an array.
            $cm_default = isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : [];

            // Exspensive.
            $is_array = is_array($cm_default);
            $default = [];
            foreach ($options as $value) {
              if ($is_array) {
                if (in_array($value, $cm_default)) {
                  $default[$value] = $value;
                }
              }
              elseif ($cm_default == $value) {
                $default[$cm_default] = $cm_default;
              }
              else {
                $default[$value] = 0;
              }
            }
            $form['CustomFields'][$form_key] = [
              '#type' => 'checkboxes',
              '#title' => SafeMarkup::checkPlain($field['FieldName']),
              '#options' => $options,
              '#default_value' => $default,
            ];
            break;
          case 'Number':
            $form['CustomFields'][$form_key] = [
              '#type' => 'textfield',
              '#title' => SafeMarkup::checkPlain($field['FieldName']),
              '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
            ];
            break;
          case 'Date':

            // Load jQuery datepicker to ensure the right date format.
            drupal_add_library('system', 'ui.datepicker');
            $form['CustomFields'][$form_key] = [
              '#type' => 'date_popup',
              '#title' => SafeMarkup::checkPlain($field['FieldName']),
              '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
              '#attributes' => [
                'class' => [
                  'campaignmonitor-date',
                ],
              ],
            ];
            break;
        }
      }
    }
    $form['list_id'] = [
      '#type' => 'hidden',
      '#default_value' => $list_id,
    ];
    return $form;
  }

  /**
   *
   */
  protected function userSelectSubscribeForm(array $form, FormStateInterface $form_state, $config = []) {
    $form = [];

    // Set options for the form.
    $form = [
      '#tree' => TRUE,
      '#attributes' => [
        'class' => [
          'campaignmonitor-subscribe-form',
          'campaignmonitor-subscribe-form-all-lists',
        ],
      ],
    ];
    $lists = campaignmonitor_get_lists();
    $options = [];
    foreach ($lists as $list_id => $list) {
      $options[$list_id] = $list['name'];
    }
    $form['selection'] = [
      '#type' => 'checkboxes',
      '#options' => $options,
      '#title' => t('Lists'),
    ];
    return $form;
  }

  /**
   * {@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();
    $config = $form_state
      ->getValue('config');
    $config = unserialize($config);
    switch ($config['list']) {
      case 'single':
        $selection = [
          $form_state
            ->getValue('list_id'),
        ];
        break;
      default:
        $selection = $form_state
          ->getValue('selection');
    }
    $CustomFields = isset($values['CustomFields']) ? $values['CustomFields'] : NULL;
    $name = isset($values['name']) ? SafeMarkup::checkPlain($values['name'])
      ->__toString() : NULL;
    $email = SafeMarkup::checkPlain($values['email'])
      ->__toString();
    foreach ($selection as $list_id) {
      if ($list_id === 0) {
        continue;
      }
      if (campaignmonitor_subscribe($list_id, $email, $name, $CustomFields)) {
        drupal_set_message(t('You are subscribed to the @name list.', [
          '@name' => $lists[$list_id]['name'],
        ]));
      }
      else {
        drupal_set_message(t('You were not subscribed to the list, please try again.'));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CampaignMonitorIcsForm::$fieldFormatter private property A reference to the field formatter used to build this form. Used to get field configuration.
CampaignMonitorIcsForm::$fieldInstance private property The campaignmonitorListsSubscription field instance used to build this form.
CampaignMonitorIcsForm::$formId private property The ID for this form. Set as class property so it can be overwritten as needed.
CampaignMonitorIcsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
CampaignMonitorIcsForm::getEditableConfigNames protected function
CampaignMonitorIcsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CampaignMonitorIcsForm::setFormID public function
CampaignMonitorIcsForm::singleSubscribeForm protected function
CampaignMonitorIcsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CampaignMonitorIcsForm::userSelectSubscribeForm protected function
CampaignMonitorIcsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.