You are here

class RecentlyReadConfigForm in Recently Read 8

Class RecentlyReadConfig.

@package Drupal\recently_read\Form

Hierarchy

Expanded class hierarchy of RecentlyReadConfigForm

1 string reference to 'RecentlyReadConfigForm'
recently_read.routing.yml in ./recently_read.routing.yml
recently_read.routing.yml

File

src/Form/RecentlyReadConfigForm.php, line 18

Namespace

Drupal\recently_read\Form
View source
class RecentlyReadConfigForm extends ConfigFormBase {

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Service entity_type.manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Service cache.default.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * Constructs RecentlyReadTypeList object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Service entity_type.manager.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cacheBackendInterface
   *   Service cache.default.
   */
  public function __construct(ConfigFactoryInterface $configFactory, EntityTypeManagerInterface $entityTypeManager, CacheBackendInterface $cacheBackendInterface) {
    parent::__construct($configFactory);
    $this->entityTypeManager = $entityTypeManager;
    $this->cache = $cacheBackendInterface;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_type.manager'), $container
      ->get('cache.default'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'delete_config',
      'delete_time',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->get('recently_read.configuration');
    $recentlyReadEntityTypes = [];

    // Get all content entity types.
    $entityTypes = $this->entityTypeManager
      ->getDefinitions();
    foreach ($entityTypes as $entityType) {
      if ($entityType
        ->getGroup() === 'content') {
        $recentlyReadEntityTypes[$entityType
          ->id()] = $entityType
          ->getLabel();
      }
    }
    $enabledEntityTypes = array_keys(RecentlyReadType::loadMultiple());
    $form['entity_types'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Entity types'),
      '#options' => $recentlyReadEntityTypes,
      '#default_value' => $enabledEntityTypes,
    ];
    $form['delete_config'] = [
      '#type' => 'radios',
      '#title' => 'Records delete options',
      '#options' => [
        'time' => $this
          ->t('Time based'),
        'count' => $this
          ->t('Count based'),
        'never' => $this
          ->t('Never'),
      ],
      '#default_value' => $config
        ->get('delete_config'),
    ];
    $delete_time_options = [
      '-1 hours' => '1 hours',
      '-1 day' => '1 day',
      '-1 week' => '1 Week',
      '-1 month' => '1 Month',
      '-1 year' => '1 Year',
    ];
    $form['delete_time'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Delete records older then'),
      '#description' => $this
        ->t('When cron is executed, delete records that are older then selected value.'),
      '#options' => $delete_time_options,
      '#default_value' => $config
        ->get('delete_time'),
      '#states' => [
        'visible' => [
          ':input[name="delete_config"]' => [
            'value' => 'time',
          ],
        ],
      ],
    ];
    $form['count'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Max records'),
      '#description' => $this
        ->t('Allowed number of records per user or session (if user is anonymous). Older records will be removed.'),
      '#default_value' => $config
        ->get('count'),
      '#states' => [
        'visible' => [
          ':input[name="delete_config"]' => [
            'value' => 'count',
          ],
        ],
        'required' => [
          ':input[name="delete_config"]' => [
            'value' => 'count',
          ],
        ],
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $selectedEntityTypes = $form_state
      ->getValue('entity_types');

    // Remove non-selected items.
    $selectedEntityTypes = array_filter($selectedEntityTypes);
    $enabledEntityTypes = array_keys(RecentlyReadType::loadMultiple());
    $toAdd = array_diff($selectedEntityTypes, $enabledEntityTypes);
    $toRemove = array_diff($enabledEntityTypes, $selectedEntityTypes);
    foreach ($toAdd as $entityType) {
      RecentlyReadType::create([
        'id' => $entityType,
        'label' => $this->entityTypeManager
          ->getDefinition($entityType)
          ->getLabel(),
      ])
        ->save();
    }
    foreach ($toRemove as $entityType) {
      $loadedRecentlyReadType = RecentlyReadType::load($entityType);
      if ($loadedRecentlyReadType) {
        $loadedRecentlyReadType
          ->delete();
      }
    }
    $config = $this->configFactory
      ->getEditable('recently_read.configuration');
    $config
      ->set('delete_config', $form_state
      ->getValue('delete_config'));
    $config
      ->set('delete_time', $form_state
      ->getValue('delete_time'));
    $config
      ->set('count', $form_state
      ->getValue('count'));
    $config
      ->save();

    // Clear caches to register the new relationship.
    $this->cache
      ->invalidateAll();
  }

}

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::$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.
RecentlyReadConfigForm::$cache protected property Service cache.default.
RecentlyReadConfigForm::$configFactory protected property The config factory service. Overrides FormBase::$configFactory
RecentlyReadConfigForm::$entityTypeManager protected property Service entity_type.manager.
RecentlyReadConfigForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
RecentlyReadConfigForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
RecentlyReadConfigForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
RecentlyReadConfigForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RecentlyReadConfigForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
RecentlyReadConfigForm::__construct public function Constructs RecentlyReadTypeList object. Overrides ConfigFormBase::__construct
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.