class WeatherDisplayForm in Weather 8
Same name and namespace in other branches
- 2.0.x src/Form/WeatherDisplayForm.php \Drupal\weather\Form\WeatherDisplayForm
Form controller for the weather_display entity edit forms.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\weather\Form\WeatherDisplayForm
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of WeatherDisplayForm
File
- src/
Form/ WeatherDisplayForm.php, line 23
Namespace
Drupal\weather\FormView 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 $block_manager;
/**
* 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->block_manager = $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->block_manager
->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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ContentEntityForm:: |
protected | property |
The entity being used by this form. Overrides EntityForm:: |
9 |
ContentEntityForm:: |
protected | property | The entity repository service. | |
ContentEntityForm:: |
protected | property | The entity type bundle info service. | |
ContentEntityForm:: |
protected | property | The time service. | |
ContentEntityForm:: |
protected | function | Add revision form fields if the entity enabled the UI. | |
ContentEntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityForm:: |
3 |
ContentEntityForm:: |
protected | function |
Copies top-level form values to entity properties Overrides EntityForm:: |
|
ContentEntityForm:: |
protected | function | Flags violations for the current form. | 4 |
ContentEntityForm:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
13 |
ContentEntityForm:: |
protected | function | Returns the bundle entity of the entity, or NULL if there is none. | |
ContentEntityForm:: |
protected | function | Gets the names of all fields edited in the form. | 4 |
ContentEntityForm:: |
public | function |
Gets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
public | function |
Gets the code identifying the active form language. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Should new revisions created on default. | |
ContentEntityForm:: |
protected | function |
Initializes the form state and the entity before the first form build. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
protected | function | Initializes form language code values. | |
ContentEntityForm:: |
public | function |
Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function |
Prepares the entity object before the form is built first. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
public | function |
Sets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Checks whether the revision form fields should be added to the form. | |
ContentEntityForm:: |
public | function | Updates the changed time of the entity. | |
ContentEntityForm:: |
public | function | Updates the form language to reflect any change to the entity language. | |
ContentEntityForm:: |
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:: |
3 |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns an array of supported actions for the current entity form. | 29 |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. | |
WeatherDisplayForm:: |
protected | property | $block_manager. | |
WeatherDisplayForm:: |
protected | property | Weather display storage. | |
WeatherDisplayForm:: |
protected | property | Weather helper service. | |
WeatherDisplayForm:: |
public | function |
Form constructor. Overrides EntityForm:: |
|
WeatherDisplayForm:: |
public static | function |
Instantiates a new instance of this class. Overrides ContentEntityForm:: |
|
WeatherDisplayForm:: |
protected | function | Finds first free display number for given display type. | |
WeatherDisplayForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
WeatherDisplayForm:: |
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:: |
|
WeatherDisplayForm:: |
public | function |
WeatherDisplayForm constructor. Overrides ContentEntityForm:: |