You are here

class SettingsForm in CRM Core 8

Same name and namespace in other branches
  1. 8.3 modules/crm_core_user_sync/src/Form/SettingsForm.php \Drupal\crm_core_user_sync\Form\SettingsForm

Configure crm_core_user_sync settings.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
crm_core_user_sync.routing.yml in modules/crm_core_user_sync/crm_core_user_sync.routing.yml
modules/crm_core_user_sync/crm_core_user_sync.routing.yml

File

modules/crm_core_user_sync/src/Form/SettingsForm.php, line 14

Namespace

Drupal\crm_core_user_sync\Form
View source
class SettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'crm_core_user_sync.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'crm_core_user_sync_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $roles = user_roles(TRUE);
    $types = IndividualType::loadMultiple();
    $config = $this
      ->config('crm_core_user_sync.settings');
    $rules = $config
      ->get('rules');
    uasort($rules, [
      $this,
      'weightCmp',
    ]);
    $form['description'] = [
      '#plain_text' => $this
        ->t('CRM Core User Synchronization can automatically create contact records associated with user accounts under certain conditions.'),
    ];
    $form['auto_sync_user_create'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Automatically create an associated contact when account is created'),
      '#description' => $this
        ->t('When checked, this checkbox will automatically create new contacts when a new user account is created according to rules listed above. Rules will be processed in order until a new contact is created.'),
      '#default_value' => $config
        ->get('auto_sync_user_create'),
    ];
    $form['contact_load'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Load contact related to the current user'),
      '#description' => $this
        ->t('When checked, contact related to the current user will be loaded as part of the user account object in $account->crm_core["contact"]. In certain situations,  loading contact data as part of a user entity can create performance issues (for instance, when there are hundreds of fields associated with each contact). Uncheck this box if it is creating problems with performance.'),
      '#default_value' => $config
        ->get('contact_load'),
    ];
    $form['contact_show'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show contact information'),
      '#description' => $this
        ->t('When checked, contact related to the current user will be shown on user profile page. Configurable from "Manage display" page.'),
      '#default_value' => $config
        ->get('contact_show'),
    ];
    $form['rules'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Role'),
        $this
          ->t('Contact type'),
        $this
          ->t('Status'),
        $this
          ->t('Operations'),
        $this
          ->t('Weight'),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'rule-weight',
        ],
      ],
      '#empty' => $this
        ->t('No rules configured'),
    ];
    foreach ($rules as $key => $rule) {
      $row = [];
      $row['#attributes']['class'][] = 'draggable';
      $row['#weight'] = $rule['weight'];
      $row['role'] = [
        '#plain_text' => $roles[$rule['role']]
          ->label(),
      ];
      $row['contact_type'] = [
        '#plain_text' => $types[$rule['contact_type']]
          ->label(),
      ];
      $row['enabled'] = [
        '#plain_text' => $rule['enabled'] ? 'Enabled' : 'Disabled',
      ];
      $row['operations'] = [
        '#type' => 'operations',
        '#links' => [],
      ];
      $row['weight'] = [
        '#type' => 'weight',
        '#title_display' => 'invisible',
        '#default_value' => $rule['weight'],
        '#attributes' => [
          'class' => [
            'rule-weight',
          ],
        ],
      ];
      $links =& $row['operations']['#links'];
      $links['edit'] = [
        'title' => 'Edit',
        'url' => Url::fromRoute('crm_core_user_sync.rule.edit', [
          'rule_key' => $key,
        ]),
      ];
      $links['delete'] = [
        'title' => 'Delete',
        'url' => Url::fromRoute('crm_core_user_sync.rule.delete', [
          'rule_key' => $key,
        ]),
      ];
      if ($rule['enabled']) {
        $links['disable'] = [
          'title' => 'Disable',
          'url' => Url::fromRoute('crm_core_user_sync.rule.disable', [
            'rule_key' => $key,
          ]),
        ];
      }
      else {
        $links['enable'] = [
          'title' => 'Enable',
          'url' => Url::fromRoute('crm_core_user_sync.rule.enable', [
            'rule_key' => $key,
          ]),
        ];
      }
      $form['rules'][$key] = $row;
    }
    $form['crm_core_user_sync_wrapper'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Sync Current Users'),
    ];
    $form['crm_core_user_sync_wrapper']['user_sync'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Synchronize Users'),
      '#submit' => [
        '::bulkUserSync',
      ],
    ];
    $form['crm_core_user_sync_wrapper']['description'] = [
      '#type' => 'item',
      '#markup' => $this
        ->t('Click this button to apply user synchronization rules to all user accounts that are currently not associated with a contact in the system. It will create an associated contact record for each user according to the rules configured above. Warning: this cannot be undone.'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Sets batch for bulk user synchronization.
   */
  public function bulkUserSync(array $form, FormStateInterface $form_state) {
    $operations[] = [
      [
        UserSyncBatch::class,
        'progress',
      ],
      [],
    ];
    $batch = [
      'operations' => $operations,
      'title' => $this
        ->t('Processing user synchronization'),
      'finished' => [
        UserSyncBatch::class,
        'finished',
      ],
    ];
    batch_set($batch);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('crm_core_user_sync.settings');
    $rules = $config
      ->get('rules');
    $rule_values = $form_state
      ->getValue('rules', []);
    if (!empty($rule_values)) {
      foreach ($rule_values as $key => $values) {
        if (!empty($values['weight'])) {
          $rules[$key]['weight'] = $values['weight'];
        }
      }
    }
    uasort($rules, [
      $this,
      'weightCmp',
    ]);
    $config
      ->set('rules', $rules)
      ->set('auto_sync_user_create', $form_state
      ->getValue('auto_sync_user_create'))
      ->set('contact_load', $form_state
      ->getValue('contact_load'))
      ->set('contact_show', $form_state
      ->getValue('contact_show'))
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Weight comparison callback.
   */
  private function weightCmp($a, $b) {
    if ($a['weight'] == $b['weight']) {
      return 0;
    }
    return $a['weight'] < $b['weight'] ? -1 : 1;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
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.
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.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::bulkUserSync public function Sets batch for bulk user synchronization.
SettingsForm::getEditableConfigNames public function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::weightCmp private function Weight comparison callback.
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.