class WeatherDisplayPlaceForm in Weather 2.0.x
Same name and namespace in other branches
- 8 src/Form/WeatherDisplayPlaceForm.php \Drupal\weather\Form\WeatherDisplayPlaceForm
Form controller for the weather_display_place entity edit forms.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, RedirectDestinationTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\weather\Form\WeatherDisplayPlaceForm
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of WeatherDisplayPlaceForm
File
- src/
Form/ WeatherDisplayPlaceForm.php, line 22
Namespace
Drupal\weather\FormView 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)) {
$type = $weather_display_place
->get($field_name)
->getFieldDefinition()
->getType();
if ($type == '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
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:: |
4 |
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 |
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:: |
4 |
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 | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
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:: |
protected | function | Returns an array of supported actions for the current entity form. | 35 |
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:: |
6 |
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:: |
3 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
12 |
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 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:: |
|
FormBase:: |
protected | property | The config factory. | 3 |
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. | 3 |
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. | |
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. | |
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. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
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. | 4 |
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. | |
WeatherDisplayPlaceForm:: |
protected | property | Weather place storage. | |
WeatherDisplayPlaceForm:: |
public | function |
Form constructor. Overrides EntityForm:: |
|
WeatherDisplayPlaceForm:: |
public | function | AJAX callback for location settings form. | |
WeatherDisplayPlaceForm:: |
public static | function |
Instantiates a new instance of this class. Overrides ContentEntityForm:: |
|
WeatherDisplayPlaceForm:: |
protected | function | Builds array of options for 'country' select. | |
WeatherDisplayPlaceForm:: |
protected | function | Builds array of options for 'place' select. | |
WeatherDisplayPlaceForm:: |
protected | function | Finds location settings for display Place form. | |
WeatherDisplayPlaceForm:: |
public | function | AJAX callback for location settings form. | |
WeatherDisplayPlaceForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
WeatherDisplayPlaceForm:: |
public | function |
WeatherDisplayForm constructor. Overrides ContentEntityForm:: |