You are here

class TrackFieldChangesAdminSettings in Track Field Changes 8

Hierarchy

Expanded class hierarchy of TrackFieldChangesAdminSettings

1 string reference to 'TrackFieldChangesAdminSettings'
track_field_changes.routing.yml in ./track_field_changes.routing.yml
track_field_changes.routing.yml

File

src/Form/TrackFieldChangesAdminSettings.php, line 14
Contains \Drupal\track_field_changes\Form\TrackFieldChangesAdminSettings.

Namespace

Drupal\track_field_changes\Form
View source
class TrackFieldChangesAdminSettings extends ConfigFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {

    // When displaying the page, make sure the list of fields is up-to-date.

    /** @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info_service */
    $bundle_info_service = \Drupal::service('entity_type.bundle.info');
    $bundle_info_service
      ->clearCachedBundles();

    /** @var \Drupal\Core\Entity\EntityFieldManager $field_manager */
    $field_manager = \Drupal::service('entity_field.manager');
    $config = $this
      ->config('track_field_changes.settings');
    $form['settings'] = [
      '#type' => 'vertical_tabs',
    ];
    $entities = \Drupal::entityTypeManager()
      ->getDefinitions();
    uasort($entities, function ($a, $b) {
      return strcmp($a
        ->getLabel(), $b
        ->getLabel());
    });
    foreach ($entities as $entity_type_id => $entity_type) {
      $form[$entity_type_id] = [
        '#type' => 'details',
        '#title' => $entity_type
          ->getLabel(),
        '#group' => 'settings',
        '#tree' => TRUE,
      ];
      $bundles = $bundle_info_service
        ->getBundleInfo($entity_type_id);
      $bundle_types = [];
      foreach ($bundles as $bundle_type_id => $bundle_type) {
        $bundle_types[$bundle_type_id] = $bundle_type['label'];
      }
      $form[$entity_type_id]['bundle_types'] = [
        '#type' => 'checkboxes',
        '#title' => t('Enable field audit on bundles'),
        '#description' => t('The bundles that should be audited.'),
        '#default_value' => array_keys($config
          ->get($entity_type_id . '.bundle_types')),
        '#options' => $bundle_types,
      ];
      foreach ($config
        ->get($entity_type_id . '.bundle_types') as $bundle_type_id) {
        if (!isset($bundles[$bundle_type_id])) {
          continue;
        }
        $options = $config
          ->get($entity_type_id . '.' . $bundle_type_id) ?: [];
        $bundle = $bundles[$bundle_type_id];
        $form[$entity_type_id][$bundle_type_id] = [
          '#type' => 'details',
          '#title' => $bundle['label'],
        ];
        $form[$entity_type_id][$bundle_type_id]['disable_multiple'] = array(
          '#type' => 'checkbox',
          '#title' => t('Disable multiple records per entity?'),
          '#description' => t('Only store one record per entity in the database. Useful to prevent views results duplication.<br>Note that if were already tracking field changes before checking this box, you will need to remove the duplicate rows manually from the database.'),
          '#default_value' => $options['disable_multiple'],
        );
        $form[$entity_type_id][$bundle_type_id]['enable_log'] = array(
          '#type' => 'checkbox',
          '#title' => t('Enable Log'),
          '#description' => t('Enable log message.'),
          '#default_value' => $options['enable_log'],
        );
        $form[$entity_type_id][$bundle_type_id]['basic_new'] = array(
          '#type' => 'checkbox',
          '#title' => t('Basic audit for created entity'),
          '#description' => t('Record basic information (timestamp, user and log) when an entity is created.'),
          '#default_value' => $options['basic_new'],
        );
        $form[$entity_type_id][$bundle_type_id]['basic_revision'] = array(
          '#type' => 'checkbox',
          '#title' => t('Basic audit for updated entity'),
          '#description' => t('Record basic information (timestamp, user and log) when an entity is updated.'),
          '#default_value' => $options['basic_revision'],
        );
        $form[$entity_type_id][$bundle_type_id]['fields_audit'] = array(
          '#type' => 'checkbox',
          '#title' => t('Track field changes for updated entity'),
          '#description' => t('Enable fields audit on updated entities. Each selected and amended field will be recorded.'),
          '#default_value' => $options['fields_audit'],
        );
        $fields = $field_manager
          ->getFieldDefinitions($entity_type_id, $bundle_type_id);
        $opts = [];
        foreach ($fields as $field_id => $field) {
          $opts[$field_id] = $field
            ->getLabel() . ' (' . $field_id . ')';
        }
        asort($opts);
        $form[$entity_type_id][$bundle_type_id]['fields'] = [
          '#type' => 'checkboxes',
          '#title' => t('Enable field audit'),
          '#description' => t('Select which fields need to be audited.'),
          '#default_value' => $options['fields'],
          '#options' => $opts,
          '#states' => [
            'visible' => [
              ':input[name="' . $entity_type_id . '[' . $bundle_type_id . '][fields_audit]"]' => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $config = $this
      ->config('track_field_changes.settings');
    foreach (\Drupal::entityTypeManager()
      ->getDefinitions() as $entity_type_id => $entity_type) {
      $vals = $form_state
        ->getValue($entity_type_id);
      $vals['bundle_types'] = array_filter($vals['bundle_types']);
      if (empty($vals['bundle_types'])) {
        $config
          ->clear($entity_type_id);
      }
      else {
        foreach ($vals as $bundle_type_id => $opts) {
          if ($bundle_type_id == 'bundle_types') {
            continue;
          }
          elseif (empty($vals[$bundle_type_id])) {
            unset($vals[$bundle_type_id]);
          }
          else {
            $vals[$bundle_type_id]['fields'] = array_filter($vals[$bundle_type_id]['fields']);
          }
        }
        $config
          ->set($entity_type_id, $vals);
      }
    }
    $config
      ->save();
    \Drupal::service('views.views_data')
      ->clear();
    parent::submitForm($form, $form_state);
  }

}

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.
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.
TrackFieldChangesAdminSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
TrackFieldChangesAdminSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
TrackFieldChangesAdminSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TrackFieldChangesAdminSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
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.