You are here

multiple_registration.module in Multiple Registration 8

File

multiple_registration.module
View source
<?php

/**
 * @file
 * Contains multiple_registration.module.
 */
use Drupal\Core\Render\Element;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\multiple_registration\Controller\MultipleRegistrationController;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Implements hook_help().
 */
function multiple_registration_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Main module help for the multiple_registration module.
    case 'help.page.multiple_registration':
      $path = dirname(__FILE__) . '/README.txt';
      if (file_exists($path)) {
        $readme = file_get_contents($path);
      }
      if (!isset($readme)) {
        return NULL;
      }
      return '<pre>' . $readme . '</pre>';
  }
}

/**
 * Implements hook_theme().
 */
function multiple_registration_theme() {
  $theme = [];
  return $theme;
}

/**
 * Implements hook_permission().
 */
function multiple_registration_permission() {
  return [
    'administer multiple_registration' => [
      'title' => t('Administer multiple registration'),
      'description' => t('Configure multiple registration module'),
    ],
  ];
}

/**
 * Implements hook_entity_operation_alter().
 */
function multiple_registration_entity_operation_alter(array &$operations, EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() === 'user_role') {
    if (\Drupal::service('router.route_provider')
      ->getRouteByName("multiple_registration.create_registration_page_form")) {
      $available_roles = \Drupal::service('multiple_registration.service')
        ->getAvailableRoles();
      if (!in_array($entity
        ->id(), array_keys($available_roles))) {
        return;
      }
      $operations['add_registration_page'] = [
        'title' => t('Add own registration page'),
        'url' => Url::fromRoute("multiple_registration.create_registration_page_form", [
          'rid' => $entity
            ->id(),
        ]),
        'weight' => 50,
      ];
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function multiple_registration_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $field = $form_state
    ->getFormObject()
    ->getEntity();
  $instance = $field;
  if ($instance
    ->get('entity_type') === 'user' && !$instance
    ->isDeleted() && !$instance
    ->isReadonly()) {
    $reg_pages = \Drupal::service('multiple_registration.service')
      ->getRegistrationPages();
    if ($reg_pages) {
      $options[MultipleRegistrationController::MULTIPLE_REGISTRATION_GENERAL_REGISTRATION_ID] = t('General registered users');
      foreach ($reg_pages as $rid => $page) {
        $options[$rid] = t('Users with %role role', [
          '%role' => $page['role_name'],
        ]);
      }
      $descr = t('Specify which of options are actual for this field. If nothing is selected, field is available for all variants.');
      $def_val = $instance
        ->getThirdPartySetting('multiple_registration', 'user_additional_register_form', []);
      $form['field']['third_party_settings']['multiple_registration'] = [
        '#type' => 'checkboxes',
        '#title' => t('This field is needed for:'),
        '#description' => $descr,
        '#default_value' => $def_val,
        '#options' => $options,
      ];
      if (!isset($form['required']['#default_value']) || !$form['required']['#default_value']) {
        $descr = t('Note: works only if "Required field" is unchecked!');
        $def_val = $instance
          ->getThirdPartySetting('multiple_registration', 'user_additional_register_form_required', []);
        $form['field']['third_party_settings']['multiple_registration_required'] = [
          '#type' => 'checkboxes',
          '#title' => t('This field is required for:'),
          '#description' => $descr,
          '#default_value' => $def_val,
          '#options' => $options,
        ];
      }
      $form['actions']['submit']['#submit'][] = 'multiple_registration_field_config_form_submit';
    }
  }
}

/**
 * Disabling of displaying fields assigned for special user roles at user page.
 *
 * @param array $variables
 *   Provides theme hook variables array.
 */
function multiple_registration_preprocess_user(array &$variables) {
  $user = $variables['elements']['#user'];

  /* @var \Drupal\user\Entity\User $user */
  $user_roles = $user
    ->getRoles();
  $fields = $user
    ->getFields();
  foreach ($fields as $field_name => $field_data) {

    /* @var Drupal\Core\Field\FieldItemList $field_data */
    $field_definition = $field_data
      ->getFieldDefinition();
    if (\property_exists($field_definition, 'third_party_settings')) {

      /* @var Drupal\field\Entity\FieldConfig $field_definition */
      $third_party_settings = $field_definition
        ->get('third_party_settings');
      if (\array_key_exists('multiple_registration', $third_party_settings)) {
        $allowed_roles = $third_party_settings['multiple_registration']['user_additional_register_form'];
        $found_roles = array_intersect($user_roles, $allowed_roles);
        if (empty($found_roles)) {
          if ($field_name !== 'user_picture') {
            unset($variables['elements'][$field_name], $variables['content'][$field_name]);
          }
        }
      }
    }
  }
}

/**
 * Form submit to save additional field settings.
 *
 * @param array $form
 *   Form data array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Form state object.
 */
function multiple_registration_field_config_form_submit(array &$form, FormStateInterface $form_state) {
  $data = $form_state
    ->getValue('multiple_registration');
  $data_required = $form_state
    ->getValue('multiple_registration_required');
  $field = $form_state
    ->getFormObject()
    ->getEntity();
  $field
    ->setThirdPartySetting('multiple_registration', 'user_additional_register_form', $data);
  $field
    ->setThirdPartySetting('multiple_registration', 'user_additional_register_form_required', $data_required);
  $field
    ->save();
}

/**
 * Implements hook_form_alter().
 */
function multiple_registration_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $storage = $form_state
    ->getStorage();
  if (!empty($storage['form_display']) && is_object($storage['form_display'])) {
    $form_display = $storage['form_display'];
    if ($form_display instanceof EntityFormDisplay && $form_display
      ->getTargetEntityTypeId() === 'user') {

      // Show only appropriate fields.
      $field_definitions = \Drupal::service('entity_field.manager')
        ->getFieldDefinitions('user', 'user');
      foreach ($field_definitions as $field_name => $field_definition) {
        if (isset($form[$field_name]) && $field_definition instanceof ThirdPartySettingsInterface) {
          $field_roles = $field_definition
            ->getThirdPartySetting('multiple_registration', 'user_additional_register_form');
          if (!empty($field_roles)) {

            // If something was selected.
            if (!(max($field_roles) === 0)) {
              $form[$field_name]['#access'] = MultipleRegistrationController::checkFieldAccess($field_roles);
            }
          }
        }
      }
    }
  }
}

/**
 * Implements hook_field_widget_form_alter().
 */
function multiple_registration_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']
    ->getFieldDefinition();
  if ($field_definition
    ->getTargetEntityTypeId() === 'user' && $field_definition instanceof ThirdPartySettingsInterface) {
    $field_roles = $field_definition
      ->getThirdPartySetting('multiple_registration', 'user_additional_register_form') ?? [];
    $field_roles_required = $field_definition
      ->getThirdPartySetting('multiple_registration', 'user_additional_register_form_required') ?? [];

    // If something was selected.
    if ($field_roles !== NULL && max($field_roles) !== 0) {
      $element['#access'] = MultipleRegistrationController::checkFieldAccess($field_roles);
    }
    if (!$element['#required'] && !empty($field_roles_required)) {

      // If something was selected.
      if (max($field_roles_required) !== 0) {
        $required = MultipleRegistrationController::checkFieldAccess($field_roles_required);
        $element['#required'] = $required;
        foreach (Element::children($element) as $child) {
          $element[$child]['#required'] = $required;
        }
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function multiple_registration_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $route_match = \Drupal::routeMatch();
  $route = $route_match
    ->getRouteName();
  if ($route == 'multiple_registration.role_registration_page') {
    $form['rid'] = [
      '#type' => 'value',
      '#value' => $route_match
        ->getParameter('rid'),
    ];
    $form['#validate'][] = 'multiple_registration_user_register_form_validate';
  }
}

/**
 * Extra form validation handler for form_user_register_form().
 */
function multiple_registration_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  $rid = $form_state
    ->getValue('rid');

  // Force enable the role to user.
  $form_state
    ->setValue([
    'roles',
    $rid,
  ], $rid);
}

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function multiple_registration_block_view_user_login_block_alter(array &$build, BlockPluginInterface $block) {
  if (isset($build['content']['user_links'])) {
    if (\Drupal::config('user.settings')
      ->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
      $reg_pages = \Drupal::service('multiple_registration.service')
        ->getRegistrationPages();
      foreach ($reg_pages as $rid => $role) {
        $uri = 'base:' . $role['url'];
        $reg_url = Url::fromUri($uri);
        $reg_link = Link::fromTextAndUrl(t('Create new @role account', [
          '@role' => $role['role_name'],
        ]), $reg_url);
        $build['content']['user_links']['#items']['multiple_registration_' . $rid] = $reg_link;
      }
    }
  }
}