You are here

class SettingsForm in Weather 8

Same name and namespace in other branches
  1. 2.0.x src/Form/SettingsForm.php \Drupal\weather\Form\SettingsForm

Configure Weather settings for this site.

Hierarchy

Expanded class hierarchy of SettingsForm

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

File

src/Form/SettingsForm.php, line 18

Namespace

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

  /**
   * Entity Type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Weather displays storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $weatherDisplayStorage;

  /**
   * Weather display places storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $weatherDisplayPlaceStorage;

  /**
   * Weather Data service.
   *
   * @var \Drupal\weather\Service\DataService
   */
  protected $weatherDataService;

  /**
   * Constructs a \Drupal\weather\Form\SettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity type manager storage.
   * @param \Drupal\weather\Service\DataService $weatherDataService
   *   Weather data service.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entityTypeManager, DataService $weatherDataService) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entityTypeManager;
    $this->weatherDisplayStorage = $entityTypeManager
      ->getStorage('weather_display');
    $this->weatherDisplayPlaceStorage = $entityTypeManager
      ->getStorage('weather_display_place');
    $this->weatherDataService = $weatherDataService;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this
      ->addWeatherDisplayOverview($form, $form_state);

    // Import/Reimport places.
    $form['import_places'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Import/Reimport places'),
    ];
    $form['import_places']['description'] = [
      '#type' => 'markup',
      '#prefix' => '<span>',
      '#markup' => $this
        ->t('After the installation, you need to import weather places into the system.'),
      '#suffix' => '</span>',
    ];
    $form['import_places']['import_places_submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import places'),
    ];

    // Additional weather settings.
    $theme = $this
      ->config('system.theme')
      ->get('default');
    $theme_path = drupal_get_path('theme', $theme);
    $config = $this
      ->config('weather.settings');
    $form['weather_image_directory'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Directory for custom images'),
      '#description' => $this
        ->t('Use custom images for displaying weather conditions. The name of this directory can be chosen freely. It will be searched in your active theme (currently %theme_path).', [
        '%theme_path' => $theme_path,
      ]),
      '#default_value' => $config
        ->get('weather_image_directory', ''),
    ];
    $options = [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      12,
      13,
      14,
    ];
    $form['weather_forecast_days'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Number of forecast days'),
      '#description' => $this
        ->t('You can configure the number of days for the forecast displays in blocks.'),
      '#default_value' => $config
        ->get('weather_forecast_days', '2'),
      '#options' => array_combine($options, $options),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Builds system wide weather displays overview.
   */
  protected function addWeatherDisplayOverview(array &$form, FormStateInterface $form_state) {
    $displays = $this->weatherDisplayStorage
      ->loadByProperties([
      'type' => WeatherDisplayInterface::SYSTEM_WIDE_TYPE,
    ]);
    foreach ($displays as $display) {
      $display_number = $display->number->value;
      $form['system_displays'][$display_number] = [
        '#type' => 'table',
        '#header' => [
          Link::fromTextAndUrl($this
            ->t('System-wide display (#@number)', [
            '@number' => $display_number,
          ]), Url::fromRoute('entity.weather_display.edit_form', [
            'display_number' => $display_number,
          ])),
          $this
            ->t('Weight'),
        ],
      ];
      $locations = $this->weatherDisplayPlaceStorage
        ->getQuery()
        ->condition('display_type', WeatherDisplayInterface::SYSTEM_WIDE_TYPE)
        ->condition('display_number', $display_number)
        ->sort('weight', 'ASC')
        ->sort('displayed_name', 'ASC')
        ->execute();
      foreach ($locations as $locationId) {
        $location = $this->weatherDisplayPlaceStorage
          ->load($locationId);
        $form['system_displays'][$display_number]['#rows'][] = [
          Link::fromTextAndUrl($location->displayed_name->value, Url::fromRoute('entity.weather_display_place.edit_form', [
            'display_type' => $location->display_type->value,
            'display_number' => $display_number,
            'weather_display_place' => $locationId,
          ])),
          $location->weight->value,
        ];
      }

      // Insert link for adding locations into the table as last row.
      $form['system_displays'][$display_number]['#rows'][] = [
        'link' => Link::fromTextAndUrl($this
          ->t('Add location to this display'), Url::fromRoute('entity.weather_display_place.add_form', [
          'display_type' => WeatherDisplayInterface::SYSTEM_WIDE_TYPE,
          'display_number' => $display_number,
        ])),
        '#wrapper_attributes' => [
          'colspan' => 2,
        ],
      ];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $triggeredBy = $form_state
      ->getTriggeringElement();
    if ($triggeredBy && $triggeredBy['#id'] == 'edit-import-places-submit') {
      $this->weatherDataService
        ->weatherDataInstallation();
    }
    else {
      $this
        ->config('weather.settings')
        ->set('weather_image_directory', $form_state
        ->getValue('weather_image_directory'))
        ->set('weather_forecast_days', $form_state
        ->getValue('weather_forecast_days'))
        ->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::$entityTypeManager protected property Entity Type manager service.
SettingsForm::$weatherDataService protected property Weather Data service.
SettingsForm::$weatherDisplayPlaceStorage protected property Weather display places storage.
SettingsForm::$weatherDisplayStorage protected property Weather displays storage.
SettingsForm::addWeatherDisplayOverview protected function Builds system wide weather displays overview.
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 \Drupal\weather\Form\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.