You are here

class LegalAdminTermsForm in Legal 8

Same name and namespace in other branches
  1. 2.0.x src/Form/LegalAdminTermsForm.php \Drupal\legal\Form\LegalAdminTermsForm

Settings form for administering content of Terms & Conditions.

Hierarchy

Expanded class hierarchy of LegalAdminTermsForm

1 string reference to 'LegalAdminTermsForm'
legal.routing.yml in ./legal.routing.yml
legal.routing.yml

File

src/Form/LegalAdminTermsForm.php, line 20

Namespace

Drupal\legal\Form
View source
class LegalAdminTermsForm extends ConfigFormBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * LegalAdminTermsForm constructor.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager, DateFormatterInterface $date_formatter) {
    parent::__construct($config_factory);
    $this->moduleHandler = $module_handler;
    $this->languageManager = $language_manager;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('module_handler'), $container
      ->get('language_manager'), $container
      ->get('date.formatter'));
  }

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

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

  /**
   * Module settings form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('legal.settings');
    $conditions = legal_get_conditions();
    $multilingual = $this->moduleHandler
      ->moduleExists('language');
    if ($multilingual) {
      $langcode = $this->languageManager
        ->getCurrentLanguage()
        ->getId();
      $conditions = legal_get_conditions($langcode);
      foreach ($this->languageManager
        ->getLanguages() as $key => $object) {
        $languages[$key] = $object
          ->getName();
      }
      $language = $langcode;
      $version_options = [
        'version' => $this
          ->t('All users (new version)'),
        'revision' => $this
          ->t('Language specific users (a revision)'),
      ];
      $version_handling = 'version';
    }
    else {
      $languages = [
        'en' => $this
          ->t('English'),
      ];
      $language = 'en';
      $version_handling = 'version';
    }
    $form['current_tc'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Current T&C'),
    ];
    if (empty($conditions['version'])) {
      $form['current_tc']['no_tc_message'] = [
        '#type' => 'html_tag',
        '#tag' => 'strong',
        '#value' => $this
          ->t('Terms & Conditions are not being displayed to users, as no T&C have been saved.'),
      ];
    }
    else {
      $form['current_tc']['#theme'] = 'legal_current_metadata';
      $form['current_tc']['current_version'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Version'),
        '#markup' => $conditions['version'],
      ];
      $form['current_tc']['current_revision'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Version'),
        '#markup' => $conditions['revision'],
      ];
      $form['current_tc']['current_language'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Language'),
        '#markup' => $conditions['language'],
      ];
      $form['current_tc']['current_date'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Created'),
        '#markup' => $this->dateFormatter
          ->format($conditions['date'], 'short'),
      ];
      $form['current_tc']['multilingual'] = [
        '#type' => 'item',
        '#markup' => $multilingual,
      ];
    }
    $form['legal_tab'] = [
      '#type' => 'vertical_tabs',
    ];
    $form['terms_of_use'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Terms of use'),
      '#group' => 'legal_tab',
    ];
    $form['terms_of_use']['conditions'] = [
      '#type' => 'text_format',
      '#title' => $this
        ->t('Terms & Conditions'),
      '#default_value' => $conditions['conditions'],
      '#description' => $this
        ->t('Your Terms & Conditions'),
      '#format' => isset($conditions['format']) ? $conditions['format'] : filter_default_format(),
      '#required' => TRUE,
    ];
    $form['registration'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Display Style Registration'),
      '#group' => 'legal_tab',
    ];

    // Override display setting.
    $form['registration']['registration_terms_style'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Display Style'),
      '#default_value' => $config
        ->get('registration_terms_style'),
      '#options' => [
        $this
          ->t('Scroll Box'),
        $this
          ->t('Scroll Box (CSS)'),
        $this
          ->t('HTML Text'),
        $this
          ->t('Page Link'),
      ],
      '#description' => $this
        ->t('How terms & conditions should be displayed to users on the registration form.'),
      '#required' => TRUE,
    ];
    $form['registration']['registration_modal_terms'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Link target'),
      '#default_value' => $config
        ->get('registration_modal_terms') === TRUE ? 1 : 0,
      '#options' => [
        0 => $this
          ->t('New window'),
        1 => $this
          ->t('Modal overlay'),
      ],
      '#description' => $this
        ->t('How to display the T&Cs when a user clicks on the link.'),
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="registration_terms_style"]' => [
            'value' => 3,
          ],
        ],
      ],
    ];
    $form['registration']['registration_container'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Display wrapped with details container'),
      '#default_value' => $config
        ->get('registration_container'),
      '#description' => $this
        ->t('How terms & conditions should be displayed to users on the registration form.'),
    ];
    $form['login'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Display Style Login'),
      '#group' => 'legal_tab',
    ];
    $form['login']['login_terms_style'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Display Style'),
      '#default_value' => $config
        ->get('login_terms_style'),
      '#options' => [
        $this
          ->t('Scroll Box'),
        $this
          ->t('Scroll Box (CSS)'),
        $this
          ->t('HTML Text'),
        $this
          ->t('Page Link'),
      ],
      '#description' => $this
        ->t('How terms & conditions should be displayed to users after the login form.'),
      '#required' => TRUE,
    ];
    $form['login']['login_modal_terms'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Link target'),
      '#default_value' => $config
        ->get('login_modal_terms') === TRUE ? 1 : 0,
      '#options' => [
        0 => $this
          ->t('New window'),
        1 => $this
          ->t('Modal overlay'),
      ],
      '#description' => $this
        ->t('How to display the T&Cs when a user clicks on the link.'),
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="login_terms_style"]' => [
            'value' => 3,
          ],
        ],
      ],
    ];
    $form['login']['login_container'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Display wrapped with details container'),
      '#default_value' => $config
        ->get('login_container'),
      '#description' => $this
        ->t('How terms & conditions should be displayed to users after the login form.'),
    ];

    // Only display options if there's more than one language available.
    if (count($languages) > 1) {

      // Language and version handling options.
      $form['language'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Language'),
        '#group' => 'legal_tab',
      ];
      $form['language']['language'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Language'),
        '#options' => $languages,
        '#default_value' => $language,
      ];
      $form['language']['version_handling'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Ask To Re-accept'),
        '#description' => $this
          ->t('<strong>All users</strong>: all users will be asked to accept the new version of the T&C, including users who accepted a previous version.<br />
                           <strong>Language specific</strong>: only new users, and users who accepted the T&C in the same language as this new revision will be asked to re-accept.'),
        '#options' => $version_options,
        '#default_value' => $version_handling,
      ];
    }
    else {
      $form['language']['language'] = [
        '#type' => 'value',
        '#value' => $language,
      ];
      $form['language']['version_handling'] = [
        '#type' => 'value',
        '#value' => $version_handling,
      ];
    }

    // Additional checkboxes.
    $form['extras'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Additional Checkboxes'),
      '#description' => $this
        ->t('Each field will be shown as a checkbox which the user must tick to register.'),
      '#open' => FALSE,
      '#tree' => TRUE,
      '#group' => 'legal_tab',
    ];
    $extras_count = count($conditions['extras']) < 10 ? 10 : count($conditions['extras']);
    for ($counter = 1; $counter <= $extras_count; $counter++) {
      $extra = isset($conditions['extras']['extras-' . $counter]) ? $conditions['extras']['extras-' . $counter] : '';
      $form['extras']['extras-' . $counter] = [
        '#type' => 'textarea',
        '#title' => $this
          ->t('Label'),
        '#default_value' => $extra,
      ];
    }

    // Notes about changes to T&C.
    $form['changes'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Explain Changes'),
      '#description' => $this
        ->t('Explain what changes were made to the T&C since the last version. This will only be shown to users who accepted a previous version. Each line will automatically be shown as a bullet point.'),
      '#group' => 'legal_tab',
    ];
    $form['changes']['changes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Changes'),
      '#default_value' => !empty($conditions['changes']) ? $conditions['changes'] : '',
    ];
    $form['preview_section'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Preview'),
      '#open' => FALSE,
    ];
    $form['preview_section']['preview'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#attributes' => [
        'id' => [
          'legal-preview',
        ],
      ],
    ];
    $form['preview_section']['trigger'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
    ];
    $form['preview_section']['trigger']['preview_button'] = [
      '#type' => 'button',
      '#value' => $this
        ->t('Preview'),
      '#ajax' => [
        'callback' => 'Drupal\\legal\\Form\\LegalAdminTermsForm::preview',
        'event' => 'click',
        'wrapper' => 'legal-preview',
        'progress' => [
          'type' => 'throbber',
          'message' => $this
            ->t('Verifying entry...'),
        ],
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();

    // Preview request, don't save anything.
    if ($form_state
      ->getTriggeringElement()['#value'] == $this
      ->t('Preview')) {
      return;
    }
    $this->configFactory
      ->getEditable('legal.settings')
      ->set('registration_terms_style', $values['registration_terms_style'])
      ->set('registration_container', $values['registration_container'])
      ->set('registration_modal_terms', $values['registration_modal_terms'])
      ->set('login_terms_style', $values['login_terms_style'])
      ->set('login_container', $values['login_container'])
      ->set('login_modal_terms', $values['login_modal_terms'])
      ->save();

    // If new conditions are different from current, enter in database.
    if ($this
      ->legalConditionsUpdated($values)) {
      $version = legal_version($values['version_handling'], $values['language']);
      Conditions::create([
        'version' => $version['version'],
        'revision' => $version['revision'],
        'language' => $values['language'],
        'conditions' => $values['conditions']['value'],
        'format' => $values['conditions']['format'],
        'date' => time(),
        'extras' => serialize($values['extras']),
        'changes' => $values['changes'],
      ])
        ->save();
      $this
        ->messenger()
        ->addMessage(t('Terms & Conditions have been saved.'));
    }
    parent::submitForm($form, $form_state);

    // @todo flush only the cache elements that need to be flushed.
    drupal_flush_all_caches();
  }

  /**
   * Check if T&Cs have been updated.
   *
   * @param array $new
   *   Newly created T&Cs.
   *
   * @return bool
   *   TRUE if the newly created T&Cs are different from the current T&Cs.
   */
  protected function legalConditionsUpdated(array $new) {
    $previous_same_language = legal_get_conditions($new['language']);
    $previous = legal_get_conditions();
    if ($previous_same_language['conditions'] != $new['conditions']['value'] && $previous['conditions'] != $new['conditions']['value']) {
      return TRUE;
    }
    $count = count($new['extras']);
    for ($counter = 1; $counter <= $count; $counter++) {
      $previous_same_language_extra = isset($previous_same_language['extras']['extras-' . $counter]) ? $previous_same_language['extras']['extras-' . $counter] : '';
      $previous_extra = isset($previous['extras']['extras-' . $counter]) ? $previous['extras']['extras-' . $counter] : '';
      if ($previous_same_language_extra != $new['extras']['extras-' . $counter] && $previous_extra != $new['extras']['extras-' . $counter]) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * Preview section wrapper.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   Returns the preview section form element.
   */
  public static function preview(array &$form, FormStateInterface $form_state) {
    $conditions = $form_state
      ->getValue('conditions');
    $extra_checkboxes = $form_state
      ->getValue('extras');
    $element['preview_section']['preview'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#attributes' => [
        'id' => [
          'legal-preview',
        ],
      ],
    ];

    // Preview the registration form.
    $element['preview_section']['preview']['registration']['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h3',
      '#value' => t('Registration'),
    ];
    $style = $form_state
      ->getValue('registration_terms_style');
    $modal = $form_state
      ->getValue('registration_modal_terms');
    $element['preview_section']['preview']['registration']['form'] = LegalAdminTermsForm::previewForm($style, $conditions, $extra_checkboxes, $modal);

    // Override accept checkbox requirement on preview.
    $element['preview_section']['preview']['registration']['form']['legal_accept']['#required'] = FALSE;

    // Preview the login form.
    $element['preview_section']['preview']['login']['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h3',
      '#value' => t('Login'),
    ];
    $style = $form_state
      ->getValue('login_terms_style');
    $modal = $form_state
      ->getValue('login_modal_terms');
    $element['preview_section']['preview']['login']['form'] = LegalAdminTermsForm::previewForm($style, $conditions, $extra_checkboxes, $modal);

    // Override accept checkbox requirement on preview.
    $element['preview_section']['preview']['login']['form']['legal_accept']['#required'] = FALSE;
    return $element;
  }

  /**
   * Form elements to be displayed as a preview of the T&C form.
   *
   * @param int $style
   *   Style that T&Cs should be displayed as.
   * @param array $conditions
   *   'value' = T&C conditions content.
   *   'format' = Format to render content with.
   * @param array $extras
   *   Each item of array to be displayed as label of a checkbox.
   * @param bool $modal
   *   Display target of Page Link option as new window or a modal overlay.
   *
   * @return array
   *   Returns the contents of the preview form element.
   */
  public static function previewForm($style, array $conditions, array $extras, $modal) {
    switch ($style) {

      // Scroll box (CSS).
      case 1:
        $form['#attached']['library'][] = 'legal/css-scroll';
        $form['conditions'] = [
          '#type' => 'html_tag',
          '#tag' => 'div',
          '#attributes' => [
            'class' => [
              'legal-terms',
              'legal-terms-scroll',
            ],
          ],
        ];
        $form['conditions']['content'] = [
          '#type' => 'processed_text',
          '#text' => $conditions['value'],
          '#format' => isset($conditions['format']) ? $conditions['format'] : filter_default_format(),
        ];
        $accept_label = legal_accept_label();
        break;

      // HTML.
      case 2:
        $form['legal_accept']['#title'] = t('<strong>Accept</strong> Terms & Conditions of Use');
        $form['conditions'] = [
          '#type' => 'html_tag',
          '#tag' => 'div',
          '#attributes' => [
            'class' => [
              'legal-terms',
            ],
          ],
        ];
        $form['conditions']['content'] = [
          '#type' => 'processed_text',
          '#text' => $conditions['value'],
          '#format' => isset($conditions['format']) ? $conditions['format'] : filter_default_format(),
        ];
        $accept_label = legal_accept_label();
        break;

      // Page Link.
      case 3:
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        $form['#attached']['library'][] = 'core/drupal.ajax';
        $form['#attached']['library'][] = 'core/jquery.form';
        $form['conditions'] = [
          '#markup' => '',
        ];
        $accept_label = legal_accept_label(TRUE, $modal);
        break;

      // Scroll box (HTML).
      default:
        $form['conditions'] = [
          '#id' => 'preview',
          '#name' => 'preview',
          '#type' => 'textarea',
          '#title' => t('Terms & Conditions'),
          '#value' => PlainTextOutput::renderFromHtml($conditions['value']),
          '#parents' => [
            'legal',
          ],
          '#rows' => 10,
          '#attributes' => [
            'readonly' => 'readonly',
          ],
        ];
        $accept_label = legal_accept_label();
    }

    // Override additional checkboxes in preview.
    if (!empty($extras)) {
      foreach ($extras as $key => $label) {
        if (!empty($label)) {
          $form[$key] = [
            '#type' => 'checkbox',
            '#title' => Xss::filter($label),
          ];
        }
      }
    }
    $form['legal_accept'] = [
      '#type' => 'checkbox',
      '#title' => $accept_label,
      '#default_value' => 0,
      '#weight' => 50,
      '#required' => TRUE,
    ];
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
LegalAdminTermsForm::$dateFormatter protected property The date formatter service.
LegalAdminTermsForm::$languageManager protected property The language manager.
LegalAdminTermsForm::$moduleHandler protected property The module handler service.
LegalAdminTermsForm::buildForm public function Module settings form. Overrides ConfigFormBase::buildForm
LegalAdminTermsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
LegalAdminTermsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
LegalAdminTermsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LegalAdminTermsForm::legalConditionsUpdated protected function Check if T&Cs have been updated.
LegalAdminTermsForm::preview public static function Preview section wrapper.
LegalAdminTermsForm::previewForm public static function Form elements to be displayed as a preview of the T&C form.
LegalAdminTermsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
LegalAdminTermsForm::__construct public function LegalAdminTermsForm constructor. Overrides ConfigFormBase::__construct
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.