You are here

class SettingsForm in Node Option Premium 8

Defines a form that configures settings.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
nopremium.routing.yml in ./nopremium.routing.yml
nopremium.routing.yml

File

src/Form/SettingsForm.php, line 16

Namespace

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

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

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

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

  /**
   * Constructs a new SettingsForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The entity display repository.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository, ModuleHandlerInterface $module_handler) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityDisplayRepository = $entity_display_repository;
    $this->moduleHandler = $module_handler;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $config = $this
      ->config('nopremium.settings');
    $form['messages'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Premium messages'),
      '#description' => $this
        ->t('You may customize the messages displayed to unprivileged users trying to view full premium contents.'),
    ];
    $form['messages']['default_message'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Default message'),
      '#description' => $this
        ->t('This message will apply to all content types with blank messages below.'),
      '#default_value' => $config
        ->get('default_message'),
      '#rows' => 3,
      '#required' => TRUE,
    ];
    foreach ($this->entityTypeManager
      ->getStorage('node_type')
      ->loadMultiple() as $content_type) {
      $form['messages']['message_' . $content_type
        ->id()] = [
        '#type' => 'textarea',
        '#title' => $this
          ->t('Message for %type content type', [
          '%type' => $content_type
            ->label(),
        ]),
        '#default_value' => $config
          ->get('messages.' . $content_type
          ->id()),
        '#rows' => 3,
      ];
    }
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['messages']['token_tree'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          'user',
          'node',
        ],
        '#weight' => 90,
      ];
    }
    else {
      $form['messages']['token_tree'] = [
        '#markup' => '<p>' . $this
          ->t('Enable the <a href="@drupal-token">Token module</a> to view the available token browser.', [
          '@drupal-token' => 'http://drupal.org/project/token',
        ]) . '</p>',
      ];
    }
    $options = [];
    foreach ($this->entityDisplayRepository
      ->getViewModes('node') as $id => $view_mode) {
      $options[$id] = $view_mode['label'];
    }
    $form['view_modes'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Premium display modes'),
      '#description' => $this
        ->t('Select for which view modes access is restricted. When none are selected, all are restricted except the view mode that is selected as "@teaser_view_mode".', [
        '@teaser_view_mode' => $this
          ->t('Teaser display mode'),
      ]),
      '#default_value' => $config
        ->get('view_modes'),
      '#options' => $options,
    ];
    $form['teaser_view_mode'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Teaser display mode'),
      '#description' => $this
        ->t('Teaser display view mode to render for premium contents.'),
      '#default_value' => $config
        ->get('teaser_view_mode'),
      '#options' => $options,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $this
      ->config('nopremium.settings')
      ->set('default_message', $values['default_message'])
      ->set('view_modes', array_filter($values['view_modes']))
      ->set('teaser_view_mode', $values['teaser_view_mode'])
      ->save();
    foreach ($this->entityTypeManager
      ->getStorage('node_type')
      ->loadMultiple() as $content_type) {
      $this
        ->config('nopremium.settings')
        ->set('messages.' . $content_type
        ->id(), $values['message_' . $content_type
        ->id()])
        ->save();
    }
    parent::submitForm($form, $form_state);
  }

}

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
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::$entityDisplayRepository protected property The entity display repository.
SettingsForm::$entityTypeManager protected property The entity type manager.
SettingsForm::$moduleHandler protected property The module handler.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
SettingsForm::getEditableConfigNames protected 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::__construct public function Constructs a new SettingsForm object. Overrides ConfigFormBase::__construct
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.