You are here

campaignmonitor_registration.module in Campaign Monitor 8.2

Select newsletter lists users want to subscribe on the registration page.

File

modules/campaignmonitor_registration/campaignmonitor_registration.module
View source
<?php

/**
 * @file
 * Select newsletter lists users want to subscribe on the registration page.
 */
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * Hooks into the registration form and adds the option to select one of the
 * available Campaign Monitor lists on registration.
 */
function campaignmonitor_registration_form_user_register_form_alter(&$form, FormStateInterface &$form_state) {
  $config = \Drupal::config('campaignmonitor_registration.settings');
  $config = $config
    ->getRawData();
  $form['campaignmonitor_subscribe'] = [
    '#type' => 'checkbox',
    '#title' => $config['checkbox_text'],
    '#attributes' => [
      'class' => [
        'campaignmonitor-subscribe',
      ],
    ],
  ];
  switch ($config['list']) {
    case 'single':
      $campaignManager = \Drupal::service('campaignmonitor.manager');

      // Get the settings for this list.
      $settings = $campaignManager
        ->getListSettings($config['list_id']);
      $campaignSubscriptionManager = \Drupal::service('campaignmonitor.subscription_manager');
      $subscription_form = $campaignSubscriptionManager
        ->singleSubscribeForm($config);

      // Drupal flattens array and we lose CustomFields on submit.
      $custom_fields = [];
      foreach ($subscription_form['CustomFields'] as $field_name => $value) {
        $custom_fields[] = $field_name;
      }
      $form['custom_fields'] = [
        '#type' => 'hidden',
        '#value' => serialize($custom_fields),
      ];

      // Make field visibility conditional.
      if (isset($subscription_form['name'])) {
        $subscription_form['name']['#states'] = [
          'visible' => [
            'input[name="campaignmonitor_subscribe"]' => [
              'checked' => TRUE,
            ],
          ],
        ];
      }
      if (isset($subscription_form['explanation'])) {
        $subscription_form['explanation']['#states'] = [
          'visible' => [
            'input[name="campaignmonitor_subscribe"]' => [
              'checked' => TRUE,
            ],
          ],
        ];
      }
      if (isset($subscription_form['CustomFields'])) {
        foreach ($subscription_form['CustomFields'] as $key => &$item) {
          $item['#states'] = [
            'visible' => [
              'input[name="campaignmonitor_subscribe"]' => [
                'checked' => TRUE,
              ],
            ],
          ];
          if ($settings['CustomFields'][$key]['required']) {
            unset($item['#required']);
            $item['#states']['required'] = [
              'input[name="campaignmonitor_subscribe"]' => [
                'checked' => TRUE,
              ],
            ];
          }
        }
      }
      $form += $subscription_form;
      break;
    default:
      $campaignManager = \Drupal::service('campaignmonitor.manager');
      $lists = $campaignManager
        ->getLists();
      $config = Drupal::config('campaignmonitor_registration.settings');

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

        // Check if the list is selected to be shown.
        $list_options = $campaignManager
          ->getListSettings($list_id);
        if ($campaignManager
          ->isListEnabled($list_id) && $list_options && isset($list_options['display']['registration']) && $list_options['display']['registration']) {
          $options[$list_id] = $list['name'];
          $defaults = $campaignManager
            ->getListSettings($list_id);
          if (isset($defaults['display']['description'])) {
            $option_descriptions[$list_id] = $defaults['display']['description'];
          }
        }
      }
      if (!empty($options)) {
        $defaults = $lists;
        $form['selection'] = [
          '#type' => 'checkboxes',
          '#description' => !empty($defaults['instructions']) ? $defaults['instructions'] : t('Select the news lists that you want to subscribe to.'),
          '#options' => $options,
          '#option_descriptions' => $option_descriptions,
          '#after_build' => [
            '_campaignmonitor_registration_option_descriptions',
          ],
        ];
      }
  }
  $form['config'] = [
    '#type' => 'hidden',
    '#value' => serialize($config),
  ];
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'campaignmonitor_registration_form_user_register_submit';
    }
  }
}

/**
 * After build callback to apply descriptions to checkbox items.
 *
 * @param Drupal\Core\Render\Element $element
 *   The elements.
 * @param Drupal\Core\Form\FormStateInterface $form_state
 *   The current s state of the form.
 *
 * @return mixed
 *   The element with description.
 */
function _campaignmonitor_registration_option_descriptions(Element $element, FormStateInterface &$form_state) {
  foreach (Element::children($element) as $key) {
    $element[$key]['#description'] = t('@description', [
      '@description' => $element['#option_descriptions'][$key],
    ]);
  }
  return $element;
}

/**
 * Submission form handler.
 *
 * Information about the selected list will be: submitted to Campaign Monitor.
 */
function campaignmonitor_registration_form_user_register_submit(&$form, FormStateInterface &$form_state) {
  $values = $form_state
    ->getValues();

  // We only act if user checked the optin.
  if (!$values['campaignmonitor_subscribe']) {
    return;
  }
  $custom_fields = unserialize($values['custom_fields']);

  // Assemble the custom fields we lost.
  foreach ($values as $field => $value) {
    if (in_array($field, $custom_fields)) {
      $values['CustomFields'][$field] = $value;
      unset($values[$field]);
    }
  }
  $form_state
    ->setValues($values);
  $campaignSubscriptionManager = \Drupal::service('campaignmonitor.subscription_manager');
  $campaignSubscriptionManager
    ->subscribeSubmitHandler($form, $form_state);
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function campaignmonitor_registration_form_campaignmonitor_list_settings_form_alter(&$form, FormStateInterface &$form_state) {

  // Find form key to index the form array and load defaults.
  $list_id = $form['listId']['#value'];
  $campaignManager = \Drupal::service('campaignmonitor.manager');
  $defaults = $campaignManager
    ->getListSettings($list_id);
  $form_key = 'campaignmonitor_list_' . $list_id;

  // Add option to enable this form on the user page.
  $form[$form_key]['display']['registration'] = [
    '#type' => 'checkbox',
    '#title' => t('Display list on registration page'),
    '#description' => t('Enable this list on the registration page and allow subscription.'),
    '#default_value' => isset($defaults['display']['registration']) ? $defaults['display']['registration'] : 0,
  ];
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'campaignmonitor_registration_form_campaignmonitor_list_settings_submit';
    }
  }
}

/**
 * Submit handler for list settings form.
 *
 * @param array $form
 *   The form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 */
function campaignmonitor_registration_form_campaignmonitor_list_settings_submit(array &$form, FormStateInterface &$form_state) {
  $list_id = $form['listId']['#value'];
  $values = $form_state
    ->getValues();
  $values = $values['campaignmonitor_list_' . $list_id];

  // These are saved remotely.
  unset($values['options']);
  $campaignManager = \Drupal::service('campaignmonitor.manager');
  $campaignManager
    ->setListSettings($list_id, $values);
}