You are here

class WeatherDisplayForm in Weather 2.0.x

Same name and namespace in other branches
  1. 8 src/Form/WeatherDisplayForm.php \Drupal\weather\Form\WeatherDisplayForm

Form controller for the weather_display entity edit forms.

Hierarchy

Expanded class hierarchy of WeatherDisplayForm

File

src/Form/WeatherDisplayForm.php, line 23

Namespace

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

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

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

  /**
   * Block manager.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected $blockManager;

  /**
   * WeatherDisplayForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\weather\Service\HelperService $weatherHelperService
   *   Weather helper 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.
   * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
   *   The block manager.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(EntityRepositoryInterface $entity_repository, HelperService $weatherHelperService, EntityTypeManagerInterface $entityTypeManager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, BlockManagerInterface $block_manager) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->weatherHelperService = $weatherHelperService;
    $this->weatherDisplayStorage = $entityTypeManager
      ->getStorage('weather_display');
    $this->blockManager = $block_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, string $display_type = '', int $display_number = 0) {
    $form = parent::buildForm($form, $form_state);
    $savedConfig = [];

    // Try to load saved config when we are editing
    // Default or User weather display.
    if ($display_type == WeatherDisplayInterface::DEFAULT_TYPE) {
      $display_number = 1;
      $defaultDisplay = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::DEFAULT_TYPE,
      ]);
      $defaultDisplay = reset($defaultDisplay);
      if ($defaultDisplay instanceof WeatherDisplayInterface) {
        $savedConfig = $defaultDisplay->config
          ->getValue()[0];
      }
    }
    elseif ($display_type == WeatherDisplayInterface::USER_TYPE) {
      $display_number = $this
        ->currentUser()
        ->id();
      $displayExists = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::USER_TYPE,
        'number' => $this
          ->currentUser()
          ->id(),
      ]);
      $systemwideDisplay = reset($displayExists);
      if ($systemwideDisplay instanceof WeatherDisplayInterface) {
        $savedConfig = $systemwideDisplay->config
          ->getValue()[0];
      }
    }
    elseif ($display_type == WeatherDisplayInterface::SYSTEM_WIDE_TYPE) {
      $displayExists = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::SYSTEM_WIDE_TYPE,
        'number' => $display_number,
      ]);
      $systemwideDisplay = reset($displayExists);
      if ($systemwideDisplay instanceof WeatherDisplayInterface) {
        $savedConfig = $systemwideDisplay->config
          ->getValue()[0];
      }
    }
    $defaultConfig = $this->weatherHelperService
      ->getDisplayConfig(WeatherDisplayInterface::DEFAULT_TYPE);
    $form['config'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Display configuration'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#tree' => TRUE,
    ];
    $form['config']['temperature'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Temperature'),
      '#description' => $this
        ->t('Unit for displaying temperatures.'),
      '#default_value' => $savedConfig['temperature'] ?? $defaultConfig['temperature'],
      '#options' => [
        'celsius' => $this
          ->t('Celsius'),
        'fahrenheit' => $this
          ->t('Fahrenheit'),
        'celsiusfahrenheit' => $this
          ->t('Celsius / Fahrenheit'),
        'fahrenheitcelsius' => $this
          ->t('Fahrenheit / Celsius'),
      ],
    ];
    $form['config']['windspeed'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Wind speed'),
      '#description' => $this
        ->t('Unit for displaying wind speeds.'),
      '#default_value' => $savedConfig['windspeed'] ?? $defaultConfig['windspeed'],
      '#options' => [
        'kmh' => $this
          ->t('km/h'),
        'mph' => $this
          ->t('mph'),
        'knots' => $this
          ->t('Knots'),
        'mps' => $this
          ->t('meter/s'),
        'beaufort' => $this
          ->t('Beaufort'),
      ],
    ];
    $form['config']['pressure'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Pressure'),
      '#description' => $this
        ->t('Unit for displaying pressure.'),
      '#default_value' => $savedConfig['pressure'] ?? $defaultConfig['pressure'],
      '#options' => [
        'hpa' => $this
          ->t('hPa'),
        'kpa' => $this
          ->t('kPa'),
        'inhg' => $this
          ->t('inHg'),
        'mmhg' => $this
          ->t('mmHg'),
      ],
    ];
    $form['config']['distance'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Distance'),
      '#description' => $this
        ->t('Unit for displaying distances.'),
      '#default_value' => $savedConfig['distance'] ?? $defaultConfig['distance'],
      '#options' => [
        'kilometers' => $this
          ->t('Kilometers'),
        'miles' => $this
          ->t('UK miles'),
      ],
    ];
    $form['config']['show_sunrise_sunset'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show times of sunrise and sunset'),
      '#default_value' => $savedConfig['show_sunrise_sunset'] ?? $defaultConfig['show_sunrise_sunset'],
      '#description' => $this
        ->t('Displays the times of sunrise and sunset. This is always the local time.'),
    ];
    $form['config']['show_windchill_temperature'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show windchill temperature'),
      '#default_value' => $savedConfig['show_windchill_temperature'] ?? $defaultConfig['show_windchill_temperature'],
      '#description' => $this
        ->t('Displays the windchill temperature. This is how the temperature <q>feels like</q>. Note that windchill temperature is only defined for temperatures below 10 °C (50 °F) and wind speeds above 1.34 m/s (3 mph).'),
    ];
    $form['config']['show_abbreviated_directions'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show abbreviated wind directions'),
      '#default_value' => $savedConfig['show_abbreviated_directions'] ?? $defaultConfig['show_abbreviated_directions'],
      '#description' => $this
        ->t('Displays abbreviated wind directions like N, SE, or W instead of North, Southeast, or West.'),
    ];
    $form['config']['show_directions_degree'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show degrees of wind directions'),
      '#default_value' => $savedConfig['show_directions_degree'] ?? $defaultConfig['show_directions_degree'],
      '#description' => $this
        ->t('Displays the degrees of wind directions, for example, North (20°).'),
    ];
    $form['type'] = [
      '#type' => 'value',
      '#value' => $display_type,
    ];
    $form['number'] = [
      '#type' => 'value',
      '#value' => $display_number,
    ];

    // Show a 'reset' button if editing the default or user display.
    if (in_array($display_type, [
      WeatherDisplayInterface::DEFAULT_TYPE,
      WeatherDisplayInterface::USER_TYPE,
    ])) {
      $form['actions']['reset'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Reset'),
        '#weight' => 10,
        '#submit' => [
          '::submitForm',
          '::save',
        ],
      ];
    }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $triggeredBy = $form_state
      ->getTriggeringElement();
    if ($triggeredBy && $triggeredBy['#id'] == 'edit-reset') {
      $defaultConfig = $this->weatherHelperService
        ->getDefaultConfig();
      $form_state
        ->setValue('config', $defaultConfig);
    }
    $this->blockManager
      ->clearCachedDefinitions();
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $type = $form_state
      ->getValue('type');
    $display_number = $form_state
      ->getValue('number');

    // Set display number before save.
    if ($form_state
      ->getValue('number') == NULL) {
      $free_number = $this
        ->getFreeDisplayNumber($type);
      $this->entity
        ->set('number', $free_number);
    }
    $this->entity
      ->set('config', $form_state
      ->getValue('config'));

    // Make sure we have only one instance of display with type 'default'.
    if ($type == WeatherDisplayInterface::DEFAULT_TYPE) {
      $defaultDisplay = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::DEFAULT_TYPE,
      ]);
      $defaultDisplay = reset($defaultDisplay);
      if ($defaultDisplay instanceof WeatherDisplayInterface) {
        $this->entity->id = $defaultDisplay
          ->id();
        $this->entity
          ->enforceIsNew(FALSE);
      }
    }
    elseif ($type == WeatherDisplayInterface::USER_TYPE) {
      $userDisplayExists = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::USER_TYPE,
        'number' => $this
          ->currentUser()
          ->id(),
      ]);
      $userDisplay = reset($userDisplayExists);
      if ($userDisplay instanceof WeatherDisplayInterface) {
        $this->entity->id = $userDisplay
          ->id();
        $this->entity
          ->enforceIsNew(FALSE);
      }
    }
    elseif ($type == WeatherDisplayInterface::SYSTEM_WIDE_TYPE) {
      $displayExists = $this->weatherDisplayStorage
        ->loadByProperties([
        'type' => WeatherDisplayInterface::SYSTEM_WIDE_TYPE,
        'number' => $display_number,
      ]);
      $systemwideDisplay = reset($displayExists);
      if ($systemwideDisplay instanceof WeatherDisplayInterface) {
        $this->entity->id = $systemwideDisplay
          ->id();
        $this->entity
          ->enforceIsNew(FALSE);
      }
    }
    $status = parent::save($form, $form_state);
    if ($status == SAVED_NEW) {
      $message = $this
        ->t('Created new Weather display');
    }
    else {
      $message = $this
        ->t('Updated existing Weather display');
    }
    $this
      ->messenger()
      ->addStatus($message);
    switch ($this->entity->type->value) {
      case WeatherDisplayInterface::USER_TYPE:
        $form_state
          ->setRedirectUrl(Url::fromRoute('weather.user.settings', [
          'user' => $this->entity->number->value,
        ]));
        break;
      default:
        $form_state
          ->setRedirectUrl(Url::fromRoute('weather.settings'));
        break;
    }
    return $status;
  }

  /**
   * Finds first free display number for given display type.
   */
  protected function getFreeDisplayNumber(string $displayType) : int {

    // User display ID is always equal UID.
    if ($displayType == WeatherDisplayInterface::USER_TYPE) {
      return $this
        ->currentUser()
        ->id();
    }

    // Find next number for system-wide display.
    $used_numbers = Database::getConnection()
      ->select('weather_display', 'wd')
      ->fields('wd', [
      'number',
    ])
      ->condition('type', $displayType)
      ->execute();
    $free_number = 1;
    foreach ($used_numbers as $row) {
      if ($row->number > $free_number) {
        break;
      }
      else {
        $free_number++;
      }
    }
    return $free_number;
  }

}

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 4
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::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
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
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::actions protected function Returns an array of supported actions for the current entity form. 35
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 6
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 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
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::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
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.
WeatherDisplayForm::$blockManager protected property Block manager.
WeatherDisplayForm::$weatherDisplayStorage protected property Weather display storage.
WeatherDisplayForm::$weatherHelperService protected property Weather helper service.
WeatherDisplayForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
WeatherDisplayForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
WeatherDisplayForm::getFreeDisplayNumber protected function Finds first free display number for given display type.
WeatherDisplayForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
WeatherDisplayForm::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 ContentEntityForm::submitForm
WeatherDisplayForm::__construct public function WeatherDisplayForm constructor. Overrides ContentEntityForm::__construct