You are here

class WeatherDisplayPlaceForm in Weather 8

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

Form controller for the weather_display_place entity edit forms.

Hierarchy

Expanded class hierarchy of WeatherDisplayPlaceForm

File

src/Form/WeatherDisplayPlaceForm.php, line 23

Namespace

Drupal\weather\Form
View source
class WeatherDisplayPlaceForm extends ContentEntityForm {

  /**
   * Weather place storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $weatherPlaceStorage;

  /**
   * WeatherDisplayForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity Type manager service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface|null $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface|null $time
   *   The time service.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeManagerInterface $entityTypeManager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->weatherPlaceStorage = $entityTypeManager
      ->getStorage('weather_place');
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $display_type = NULL, $display_number = NULL, WeatherDisplayPlaceInterface $weather_display_place = NULL) {

    // Check if we have weather places to connect with displays.
    $weatherPlacesExists = $this->weatherPlaceStorage
      ->getQuery()
      ->range(0, 1)
      ->execute();
    if (empty($weatherPlacesExists)) {
      $form['no_places_added'] = [
        '#markup' => $this
          ->t('You do not have any weather places in system. Go to <a href="@url">settings page</a> and run weather places import', [
          '@url' => Url::fromRoute('weather.settings')
            ->toString(),
        ]),
      ];
      return $form;
    }
    if ($display_type == WeatherDisplayInterface::USER_TYPE) {
      $display_number = $this
        ->currentUser()
        ->id();
    }
    $form = parent::buildForm($form, $form_state);

    // If we are on edit form, display type and number not passed here.
    if ($weather_display_place instanceof WeatherDisplayPlaceInterface) {
      $display_type = $weather_display_place->display_type->value;
      $display_number = $weather_display_place->display_number->value;
    }

    // If the place exists, get the configuration.
    // If it does not exist - get the default place configuration.
    $settings = $this
      ->getLocationSettings($weather_display_place);
    if (!empty($form_state
      ->getValue('country'))) {
      $settings['country'] = $form_state
        ->getValue('country');
    }
    $settings['places'] = $this
      ->getAvailablePlacesOptions($settings['country']);
    $form['country'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Country'),
      '#description' => $this
        ->t('Select a country to narrow down your search.'),
      '#default_value' => $settings['country'],
      '#options' => $this
        ->getAvailableCountriesOptions(),
      '#ajax' => [
        'callback' => '::countryAjaxCallback',
        'wrapper' => 'weather_place_replace',
      ],
    ];
    $form['geoid'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Place'),
      '#description' => $this
        ->t('Select a place in that country for the weather display.'),
      '#default_value' => $settings['geoid'],
      '#options' => $settings['places'],
      '#prefix' => '<div id="weather_place_replace">',
      '#ajax' => [
        'callback' => '::placeAjaxCallback',
        'wrapper' => 'weather_displayed_name_replace',
      ],
    ];
    $form['displayed_name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Displayed name for the selected place'),
      '#default_value' => $settings['displayed_name'],
      '#description' => $this
        ->t('You may enter another name for the place selected above.'),
      '#required' => TRUE,
      '#size' => '30',
      '#prefix' => '<div id="weather_displayed_name_replace">',
      '#suffix' => '</div></div>',
    ];
    $form['weight'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Weight'),
      '#default_value' => $settings['weight'],
      '#description' => $this
        ->t('Optional. In the block, the heavier locations will sink and the lighter locations will be positioned nearer the top. Locations with equal weights are sorted alphabetically.'),
    ];
    $form['display_type'] = [
      '#type' => 'value',
      '#value' => $display_type,
    ];
    $form['display_number'] = [
      '#type' => 'value',
      '#value' => $display_number,
    ];

    // If the form is regenerated during an AJAX callback, get the
    // country selected by the user.
    if ($triggeredBy = $form_state
      ->getTriggeringElement()) {
      $settings['country'] = $form_state
        ->getValue('country');
      if ($triggeredBy["#name"] == 'country') {
        $settings['places'] = $this
          ->getAvailablePlacesOptions($settings['country']);
        $settings['geoid'] = key($settings['places']);
        $settings['displayed_name'] = $settings['places'][$settings['geoid']];
        $form['geoid']['#options'] = $settings['places'];
        $form['geoid']['#value'] = $settings['geoid'];
        $form['displayed_name']['#value'] = $settings['displayed_name'];
      }
      if ($triggeredBy["#name"] == 'geoid') {
        $settings['displayed_name'] = $settings['places'][$form_state
          ->getValue('geoid')];
        $form['displayed_name']['#value'] = $settings['displayed_name'];
      }
    }

    // Use different path for delete form for non-admin user.
    if ($display_type == WeatherDisplayInterface::USER_TYPE && $weather_display_place instanceof WeatherDisplayPlaceInterface) {
      $form["actions"]["delete"]["#url"] = Url::fromRoute('weather.user.weather_display_place.delete_form', [
        'user' => $display_number,
        'weather_display_place' => $weather_display_place
          ->id(),
      ]);
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);

    // Invalidate related weather display cache, once place is saved.
    $display_type = $this->entity->display_type->value;
    $display_number = $this->entity->display_number->value;
    $displays = $this->entityTypeManager
      ->getStorage('weather_display')
      ->loadByProperties([
      'type' => $display_type,
      'number' => $display_number,
    ]);
    foreach ($displays as $display) {
      $tags = $display
        ->getCacheTags();

      // Separately invalidate cache_tag for user. For correct page update after adding new location.
      $tags[] = 'weather_display:' . $this
        ->currentUser()
        ->id();
      Cache::invalidateTags($tags);
    }

    // Show message.
    if ($status == SAVED_NEW) {
      $message = $this
        ->t('Added new place to weather display');
    }
    else {
      $message = $this
        ->t('Updated existing place in weather display');
    }
    $this
      ->messenger()
      ->addStatus($message);
    switch ($this->entity->display_type->value) {
      case WeatherDisplayInterface::USER_TYPE:
        $form_state
          ->setRedirectUrl(Url::fromRoute('weather.user.settings', [
          'user' => $this->entity->display_number->value,
        ]));
        break;
      default:
        $form_state
          ->setRedirectUrl(Url::fromRoute('weather.settings'));
        break;
    }
    return $status;
  }

  /**
   * Finds location settings for display Place form.
   *
   * @param \Drupal\weather\Entity\WeatherDisplayPlaceInterface|null $weather_display_place
   *   Weather display place entity.
   *
   * @return array
   *   Settings.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getLocationSettings(WeatherDisplayPlaceInterface $weather_display_place = NULL) {

    // Set defaults.
    $settings = [
      'geoid' => 'geonames_703448',
      'displayed_name' => 'Kyiv',
      'weight' => 0,
      'country' => 'Ukraine',
    ];
    if ($weather_display_place instanceof WeatherDisplayPlaceInterface) {
      foreach ($settings as $field_name => $value) {
        if ($weather_display_place
          ->hasField($field_name)) {
          if ($weather_display_place
            ->get($field_name)
            ->getFieldDefinition()
            ->getType() == 'entity_reference') {
            $settings[$field_name] = $weather_display_place->{$field_name}->target_id;
          }
          else {
            $settings[$field_name] = $weather_display_place->{$field_name}->value;
          }
        }
      }

      // Find related country.
      $place = $this->entityTypeManager
        ->getStorage('weather_place')
        ->load($settings['geoid']);
      $settings['country'] = $place->country->value;
    }
    return $settings;
  }

  /**
   * Builds array of options for 'country' select.
   */
  protected function getAvailableCountriesOptions() {
    $result = $this->weatherPlaceStorage
      ->getAggregateQuery()
      ->groupBy('country')
      ->sort('country', 'ASC')
      ->execute();
    foreach ($result as $row) {
      $countries[$row['country']] = $row['country'];
    }
    return $countries;
  }

  /**
   * Builds array of options for 'place' select.
   */
  protected function getAvailablePlacesOptions(string $country) {
    $places = [];
    $result = $this->weatherPlaceStorage
      ->getQuery()
      ->condition('country', $country)
      ->sort('name', 'ASC')
      ->execute();
    foreach ($result as $id) {
      $place = $this->weatherPlaceStorage
        ->load($id);
      $places[$place->geoid->value] = $place->name->value;
    }
    return $places;
  }

  /**
   * AJAX callback for location settings form.
   */
  public function countryAjaxCallback(array &$form, FormStateInterface $form_state) {
    $ret['geoid'] = $form['geoid'];
    $ret['displayed_name'] = $form['displayed_name'];
    return $ret;
  }

  /**
   * AJAX callback for location settings form.
   */
  public function placeAjaxCallback($form, $form_state) {
    return $form['displayed_name'];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity 3
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form 13
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm 3
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
ContentEntityForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides FormBase::validateForm 3
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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.
WeatherDisplayPlaceForm::$weatherPlaceStorage protected property Weather place storage.
WeatherDisplayPlaceForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
WeatherDisplayPlaceForm::countryAjaxCallback public function AJAX callback for location settings form.
WeatherDisplayPlaceForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
WeatherDisplayPlaceForm::getAvailableCountriesOptions protected function Builds array of options for 'country' select.
WeatherDisplayPlaceForm::getAvailablePlacesOptions protected function Builds array of options for 'place' select.
WeatherDisplayPlaceForm::getLocationSettings protected function Finds location settings for display Place form.
WeatherDisplayPlaceForm::placeAjaxCallback public function AJAX callback for location settings form.
WeatherDisplayPlaceForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
WeatherDisplayPlaceForm::__construct public function WeatherDisplayForm constructor. Overrides ContentEntityForm::__construct