You are here

class MessageBannerSettingsForm in Message Banner 8

The message banner settings form.

Hierarchy

Expanded class hierarchy of MessageBannerSettingsForm

1 string reference to 'MessageBannerSettingsForm'
message_banner.routing.yml in ./message_banner.routing.yml
message_banner.routing.yml

File

src/Form/MessageBannerSettingsForm.php, line 15

Namespace

Drupal\message_banner\Form
View source
class MessageBannerSettingsForm extends ConfigFormBase {

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

  /**
   * The state storage service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return 'message_banner.settings';
  }

  /**
   * Constructs a message banner settings form.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state storage service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state) {
    parent::__construct($config_factory);
    $this->moduleHandler = $module_handler;
    $this->state = $state;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) : array {
    $config = $this
      ->config('message_banner.settings');
    $form['banner_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable banner'),
      '#default_value' => $config
        ->get('banner_enabled') ?: FALSE,
    ];
    $form['message_banner'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Message banner settings'),
      '#states' => [
        'visible' => [
          ':input[name="banner_enabled"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['message_banner']['banner_enabled_on_admin_routes'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable banner on admin routes'),
      '#description' => $this
        ->t('If not checked, the banner will only appear on non-admin routes.'),
      '#default_value' => $config
        ->get('banner_enabled_on_admin_routes') ?: FALSE,
      '#states' => [
        'visible' => [
          ':input[name="banner_enabled"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['message_banner']['banner_show_again_minutes'] = [
      '#type' => 'number',
      '#step' => 1,
      '#title' => $this
        ->t('Minutes before showing banner after dismissing it'),
      '#default_value' => $config
        ->get('banner_show_again_minutes'),
      '#description' => $this
        ->t('The number of minutes to elapse after dimissing the banner before showing it again (0 to disable).'),
    ];
    $form['message_banner']['banner_color'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Banner color'),
      '#description' => $this
        ->t('Choose the background color for the banner.'),
      '#options' => $this
        ->getBannerColors(),
      '#default_value' => $config
        ->get('banner_color') ?: NULL,
      '#states' => [
        'required' => [
          ':input[name="banner_enabled"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['message_banner']['banner_text'] = [
      '#type' => 'text_format',
      '#title' => $this
        ->t('Message'),
      '#description' => $this
        ->t('This message will be shown to every site visitor, so make sure it does not contain any sensitive information!'),
      '#default_value' => $config
        ->get('banner_text.value') ?: '',
      '#format' => $config
        ->get('banner_text.format') ?: 'basic_html',
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->config('message_banner.settings')
      ->set('banner_enabled', $form_state
      ->getValue('banner_enabled'))
      ->set('banner_enabled_on_admin_routes', $form_state
      ->getValue('banner_enabled_on_admin_routes'))
      ->set('banner_color', $form_state
      ->getValue('banner_color'))
      ->set('banner_text', $form_state
      ->getValue('banner_text'))
      ->set('banner_show_again_minutes', $form_state
      ->getValue('banner_show_again_minutes'))
      ->save();

    // Save the save time as a state value, so that config is not affected.
    $this->state
      ->set('banner_saved', time());
    return parent::submitForm($form, $form_state);
  }

  /**
   * Gets the available colors for the message banner.
   *
   * @see hook_message_banner_colors_alter()
   *
   * @return array
   *   An array of background colors.
   */
  protected function getBannerColors() : array {
    $colors = [
      'default--red' => $this
        ->t('Red'),
      'default--amber' => $this
        ->t('Amber'),
      'default--green' => $this
        ->t('Green'),
      'default--black' => $this
        ->t('Black'),
      'default--gray' => $this
        ->t('Gray'),
      'default--white' => $this
        ->t('White'),
    ];

    // Allow other developers to add extra colors, such as brand colors.
    $this->moduleHandler
      ->alter('message_banner_colors', $colors);
    return $colors;
  }

}

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.
MessageBannerSettingsForm::$moduleHandler protected property The module handler.
MessageBannerSettingsForm::$state protected property The state storage service.
MessageBannerSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
MessageBannerSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
MessageBannerSettingsForm::getBannerColors protected function Gets the available colors for the message banner.
MessageBannerSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
MessageBannerSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MessageBannerSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
MessageBannerSettingsForm::__construct public function Constructs a message banner settings form. Overrides ConfigFormBase::__construct
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.