You are here

class AdminSettingsForm in Exclude Node Title 8

Form object class for Exclude Node Title settings.

Hierarchy

Expanded class hierarchy of AdminSettingsForm

1 string reference to 'AdminSettingsForm'
exclude_node_title.routing.yml in ./exclude_node_title.routing.yml
exclude_node_title.routing.yml

File

src/Form/AdminSettingsForm.php, line 19

Namespace

Drupal\exclude_node_title\Form
View source
class AdminSettingsForm extends ConfigFormBase {

  /**
   * The Exclude Node Title module settings manager.
   *
   * @var \Drupal\exclude_node_title\ExcludeNodeTitleManagerInterface
   */
  protected $excludeNodeTitleManager;

  /**
   * Discovery and retrieval of entity type bundles manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $bundleInfo;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Defines the interface for a configuration object factory.
   * @param \Drupal\exclude_node_title\ExcludeNodeTitleManagerInterface $exclude_node_title_manager
   *   The Exclude Node Title module settings manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_bundle_info
   *   Discovery and retrieval of entity type bundles manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The entity display repository.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ExcludeNodeTitleManagerInterface $exclude_node_title_manager, EntityTypeBundleInfoInterface $entity_bundle_info, EntityDisplayRepositoryInterface $entity_display_repository) {
    parent::__construct($config_factory);
    $this->excludeNodeTitleManager = $exclude_node_title_manager;
    $this->bundleInfo = $entity_bundle_info;
    $this->entityDisplayRepository = $entity_display_repository;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $enabled_link = Link::fromTextAndUrl(t('Search module'), Url::fromRoute('system.modules_list', [], [
      'fragment' => 'module-search',
    ]))
      ->toString();
    $form['#attached']['library'][] = 'system/drupal.system';
    $form['exclude_node_title_search'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Remove node title from search pages'),
      '#description' => $this
        ->t('You need to have @searchmodule enabled.', [
        '@searchmodule' => $enabled_link,
      ]),
      '#default_value' => $this->excludeNodeTitleManager
        ->isSearchExcluded(),
      '#disabled' => !\Drupal::moduleHandler()
        ->moduleExists('search'),
    ];
    $form['render_type'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Type of rendering'),
      '#options' => [
        'remove' => $this
          ->t('Remove text'),
        'hidden' => $this
          ->t('Hidden class'),
      ],
      '#description' => $this
        ->t('Remove text will remove all text within the title. This may leave the HTML tag. Hidden class will add a <code>.hidden</code> class to the HTML tag where appropriate.'),
      '#default_value' => $this->excludeNodeTitleManager
        ->getRenderType(),
    ];
    $form['content_type'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Exclude title by content types'),
      '#description' => $this
        ->t('<strong>All nodes..</strong> excludes the Node title from all of the node displays using the View Mode(s) you select.<br /><strong>User defined nodes..</strong> does not, by default, hide any Node title. However, it provides users with the permission to exclude node title a checkbox on the node edit form that allows them to exclude node titles, from the View Modes selected in this form, on a node-by-node basis.'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#tree' => TRUE,
    ];
    foreach ($this->bundleInfo
      ->getBundleInfo('node') as $node_type => $node_type_info) {
      $form['#attached']['drupalSettings']['exclude_node_title']['content_types'][$node_type] = $node_type_info['label'];
      $form['content_type'][$node_type]['content_type_value'] = [
        '#type' => 'select',
        '#title' => $node_type_info['label'],
        '#default_value' => $this->excludeNodeTitleManager
          ->getBundleExcludeMode($node_type),
        '#options' => [
          'none' => $this
            ->t('None'),
          'all' => $this
            ->t('All nodes...'),
          'user' => $this
            ->t('User defined nodes...'),
        ],
      ];
      $entity_view_modes = $this->entityDisplayRepository
        ->getViewModes('node');
      $modes = [];
      foreach ($entity_view_modes as $view_mode_name => $view_mode_info) {
        $modes[$view_mode_name] = $view_mode_info['label'];
      }
      $modes += [
        'nodeform' => $this
          ->t('Node form'),
      ];
      switch ($form['content_type'][$node_type]['content_type_value']['#default_value']) {
        case 'all':
          $title = $this
            ->t('Exclude title from all nodes in the following view modes:');
          break;
        case 'user defined':
          $title = $this
            ->t('Exclude title from user defined nodes in the following view modes:');
          break;
        default:
          $title = $this
            ->t('Exclude from:');
      }
      $form['content_type'][$node_type]['content_type_modes'] = [
        '#type' => 'checkboxes',
        '#title' => $title,
        '#default_value' => $this->excludeNodeTitleManager
          ->getExcludedViewModes($node_type),
        '#options' => $modes,
        '#states' => [
          // Hide the modes when the content type value is <none>.
          'invisible' => [
            'select[name="content_type[' . $node_type . '][content_type_value]"]' => [
              'value' => 'none',
            ],
          ],
        ],
      ];
    }
    $form['#attached']['library'][] = 'exclude_node_title/drupal.exclude_node_title.admin';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = \Drupal::configFactory()
      ->getEditable('exclude_node_title.settings');
    $values = $form_state
      ->getValues();
    foreach ($values['content_type'] as $node_type => $value) {
      $modes = array_filter($values['content_type'][$node_type]['content_type_modes']);
      $modes = array_keys($modes);
      $config
        ->set('content_types.' . $node_type, $values['content_type'][$node_type]['content_type_value'])
        ->set('content_type_modes.' . $node_type, $modes);
    }
    $config
      ->set('search', $values['exclude_node_title_search'])
      ->set('type', $values['render_type'])
      ->save();
    parent::submitForm($form, $form_state);
    foreach (Cache::getBins() as $service_id => $cache_backend) {
      $cache_backend
        ->deleteAll();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AdminSettingsForm::$bundleInfo protected property Discovery and retrieval of entity type bundles manager.
AdminSettingsForm::$entityDisplayRepository protected property The entity display repository.
AdminSettingsForm::$excludeNodeTitleManager protected property The Exclude Node Title module settings manager.
AdminSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AdminSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AdminSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AdminSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AdminSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AdminSettingsForm::__construct public function Overrides ConfigFormBase::__construct
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.
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.