You are here

class AddCustomPlaceForm in Weather 8

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

Configure Weather settings for this site.

Hierarchy

Expanded class hierarchy of AddCustomPlaceForm

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

File

src/Form/AddCustomPlaceForm.php, line 19

Namespace

Drupal\weather\Form
View source
class AddCustomPlaceForm extends FormBase {

  /**
   * 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;

  /**
   * Weather helper service.
   *
   * @var \Drupal\weather\Service\HelperService
   */
  protected $weatherHelper;

  /**
   * Parser service.
   *
   * @var \Drupal\weather\Service\ParserService
   */
  protected $weatherParser;

  /**
   * Constructs a \Drupal\weather\Form\SettingsForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity type manager storage.
   * @param \Drupal\weather\Service\DataService $weatherDataService
   *   Weather data service.
   * @param \Drupal\weather\Service\HelperService $helperService
   *   Weather helper service.
   * @param \Drupal\weather\Service\ParserService $parserService
   *   Weather parser service.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   Drupal messenegr service.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, DataService $weatherDataService, HelperService $helperService, ParserService $parserService, MessengerInterface $messenger) {
    $this->entityTypeManager = $entityTypeManager;
    $this->weatherDisplayStorage = $entityTypeManager
      ->getStorage('weather_display');
    $this->weatherDisplayPlaceStorage = $entityTypeManager
      ->getStorage('weather_display_place');
    $this->weatherDataService = $weatherDataService;
    $this->weatherHelper = $helperService;
    $this->weatherParser = $parserService;
    $this->messenger = $messenger;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $placesStorage = $this->entityTypeManager
      ->getStorage('weather_place');
    $form['weather_yrno_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('URL of English weather forecast on yr.no'),
      '#description' => $this
        ->t('Example: https://www.yr.no/place/Ukraine/Kiev/Kyiv/.'),
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save place'),
    ];

    // Create tables for modified places.
    $tables = [
      WeatherPlaceInterface::STATUS_ADDED => t('Added places'),
      WeatherPlaceInterface::STATUS_MODIFIED => t('Modified places'),
    ];
    foreach ($tables as $status => $caption) {
      $header = [
        $this
          ->t('GeoID'),
        $this
          ->t('Latitude'),
        $this
          ->t('Longitude'),
        $this
          ->t('Country'),
        $this
          ->t('Name'),
        $this
          ->t('Link'),
      ];
      $rows = [];
      $result = $placesStorage
        ->getQuery()
        ->condition('status', $status)
        ->sort('country', 'ASC')
        ->sort('name', 'ASC')
        ->execute();
      if (!empty($result)) {
        foreach ($placesStorage
          ->loadMultiple($result) as $place) {
          $rows[] = [
            $place->geoid->value,
            $place->latitude->value,
            $place->longitude->value,
            $place->country->value,
            $place->name->value,
            $place->link->value,
          ];
        }
        $form['places'][] = [
          '#theme' => 'table',
          '#header' => $header,
          '#rows' => $rows,
          '#caption' => $caption,
          '#empty' => $this
            ->t('No places.'),
        ];
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Remove whitespaces.
    $url = trim($form_state
      ->getValue('weather_yrno_url'));

    // Check for the english version.
    if (substr($url, 0, 24) != 'https://www.yr.no/place/') {
      $form_state
        ->setErrorByName('weather_yrno_url', $this
        ->t('Please make sure to use the English version of the forecast, starting with "https://www.yr.no/<strong>place</strong>/".'));
    }
    list($country, $link) = $this->weatherHelper
      ->parsePlaceUrl($url);
    $placeExists = $this->entityTypeManager
      ->getStorage('weather_place')
      ->getQuery()
      ->condition('country', $country)
      ->condition('link', $link)
      ->execute();
    if ($placeExists) {
      $form_state
        ->setErrorByName('weather_yrno_url', $this
        ->t('The place is already in the database'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = $form_state
      ->getValue('weather_yrno_url');
    $url = trim($url) . 'forecast.xml';
    if ($this->weatherParser
      ->downloadForecast('', $url)) {
      $this->messenger
        ->addStatus($this
        ->t('The new place has been saved.'));
    }
    else {
      $this->messenger
        ->addError($this
        ->t('The download from the given URL did not succeed.'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddCustomPlaceForm::$entityTypeManager protected property Entity Type manager service.
AddCustomPlaceForm::$weatherDataService protected property Weather Data service.
AddCustomPlaceForm::$weatherDisplayPlaceStorage protected property Weather display places storage.
AddCustomPlaceForm::$weatherDisplayStorage protected property Weather displays storage.
AddCustomPlaceForm::$weatherHelper protected property Weather helper service.
AddCustomPlaceForm::$weatherParser protected property Parser service.
AddCustomPlaceForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
AddCustomPlaceForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
AddCustomPlaceForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AddCustomPlaceForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AddCustomPlaceForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
AddCustomPlaceForm::__construct public function Constructs a \Drupal\weather\Form\SettingsForm 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::config protected function Retrieves a configuration object.
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.
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.