You are here

class SettingsForm in Geolocation Address Link 8

Class SettingsForm.

@package Drupal\geolocation_address_link\Form

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
geolocation_address_link.routing.yml in ./geolocation_address_link.routing.yml
geolocation_address_link.routing.yml

File

src/Form/SettingsForm.php, line 18

Namespace

Drupal\geolocation_address_link\Form
View source
class SettingsForm extends ConfigFormBase {

  /**
   * @var Drupal\Core\Entity\EntityFieldManager
   */
  protected $field_manager;

  /**
   * @var Drupal\Core\Entity\EntityTypeBundleInfo
   */
  protected $bundle_info;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityFieldManager $field_manager, EntityTypeBundleInfo $bundle_info) {
    parent::__construct($config_factory);
    $this->field_manager = $field_manager;
    $this->bundle_info = $bundle_info;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->get('geolocation_address_link.settings');
    $form['container'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Geolocation Address Link Settings'),
      '#description' => $this
        ->t('<p>Each entity type that uses this functionality needs two special fields: <ol><li>The usual address field to allow the user to input an address.</li><li>A geolocation field that contains the geocoordinates of the address.</li></ol></p><p>When the entity is saved, any value in the address field will be used to automatically update the geo coordinates in the related geolocation field. Hide the geolocation field on the entity edit form since the user will not actually be able to update it manually.</p>'),
    ];

    // Field all address fields in this Drupal installation.
    $field_map = $this->field_manager
      ->getFieldMapByFieldType('address');
    $options = [];
    foreach ($field_map as $entity_type => $entity_map) {
      $bundle_info = $this->bundle_info
        ->getBundleInfo($entity_type);
      foreach ($entity_map as $field_name => $data) {
        foreach ($data['bundles'] as $bundle) {
          if ($info = FieldConfig::loadByName($entity_type, $bundle, $field_name)) {
            $key = $entity_type . ':' . $bundle;
            $bundle_name = $bundle_info[$bundle]['label'] . ' (' . $entity_type . ')';
            $options[$bundle_name][$entity_type][$bundle][$field_name] = $info
              ->getLabel() . ' (' . $info
              ->getName() . ')';
          }
        }
      }
    }
    ksort($options);

    // Find all geolocation fields in this Drupal installation.
    $field_map = $this->field_manager
      ->getFieldMapByFieldType('geolocation');
    $options2 = [];
    foreach ($field_map as $entity_type => $entity_map) {
      $bundle_info = $this->bundle_info
        ->getBundleInfo($entity_type);
      foreach ($entity_map as $field_name => $data) {
        foreach ($data['bundles'] as $bundle) {
          if ($info = FieldConfig::loadByName($entity_type, $bundle, $field_name)) {
            $bundle_name = $bundle_info[$bundle]['label'] . ' (' . $entity_type . ')';
            $options2[$bundle_name][$entity_type][$bundle][$field_name] = $info
              ->getLabel() . ' (' . $info
              ->getName() . ')';
          }
        }
      }
    }
    ksort($options2);

    // Create an array of bundles that have both an address field and a
    // geolocation field as the possible fields that can be mapped to each
    // other.
    $combined = [];
    foreach ($options as $label => $labels) {
      foreach ($labels as $entity_type => $types) {
        foreach ($types as $bundle => $bundles) {
          foreach ($bundles as $field_name => $value) {
            if (array_key_exists($label, $options2)) {
              foreach ($options2[$label][$entity_type][$bundle] as $field_name2 => $value2) {
                if (array_key_exists($label, $options) && array_key_exists($entity_type, $options[$label]) && array_key_exists($bundle, $options[$label][$entity_type])) {
                  $combined[$label][$entity_type . ':' . $bundle . ':' . $field_name . ':' . $field_name2] = $value . ' -> ' . $value2;
                }
              }
            }
          }
        }
      }
    }
    $form['container']['fields'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Field(s)'),
      '#description' => $this
        ->t('Select the field combination(s) that should be updated when the entity is saved. The values in the address field on the left will be used to update the geolocation coordinates in the geolocation field on the right. Note that any previous value in the geolocation field will be wiped out by this update!'),
      '#default_value' => $config
        ->get('fields'),
      '#options' => $combined,
      '#multiple' => TRUE,
    ];
    return parent::buildForm($form, $form_state);
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'geolocation_address_link.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this
      ->config('geolocation_address_link.settings')
      ->set('fields', $form_state
      ->getValue('fields'))
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration 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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
SettingsForm::$bundle_info protected property
SettingsForm::$field_manager protected property
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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.