You are here

class GeolocationSettings in Geolocation Field 8

Implements the GeolocationGoogleMapAPIkey form controller.

Hierarchy

Expanded class hierarchy of GeolocationSettings

See also

\Drupal\Core\Form\FormBase

1 string reference to 'GeolocationSettings'
geolocation.routing.yml in ./geolocation.routing.yml
geolocation.routing.yml

File

src/Form/GeolocationSettings.php, line 14

Namespace

Drupal\geolocation\Form
View source
class GeolocationSettings extends ConfigFormBase {
  use GoogleMapsDisplayTrait;

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->get('geolocation.settings');
    $form['#tree'] = TRUE;
    $form['google_map_api_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Google Maps API key'),
      '#default_value' => $config
        ->get('google_map_api_key'),
      '#description' => $this
        ->t('Google requires users to use a valid API key. Using the <a href="https://console.developers.google.com/apis">Google API Manager</a>, you can enable the <em>Google Maps JavaScript API</em>. That will create (or reuse) a <em>Browser key</em> which you can paste here.'),
    ];
    $form['google_map_api_server_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Google Maps API Server key'),
      '#default_value' => $config
        ->get('google_map_api_server_key'),
      '#description' => $this
        ->t('If you use a separate key for server-side operations, add it here. Leave empty to use the Google Maps API key as above.'),
    ];
    $custom_parameters = $config
      ->get('google_map_custom_url_parameters');
    $form['parameters'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Optional Google Parameters'),
      '#description' => $this
        ->t('None of these parameters is required. Please note: modules might extend or override these options.'),
      '#open' => !empty($custom_parameters),
    ];
    $form['parameters']['libraries'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t("Google Maps Libraries - 'libraries'"),
      '#description' => $this
        ->t('See <a href=":google_libraries_link">Google libraries documentation</a>.', [
        ':google_libraries_link' => 'https://developers.google.com/maps/documentation/javascript/libraries',
      ]),
      '#attributes' => [
        'id' => 'geolocation-google-libraries',
      ],
    ];
    $module_parameters = \Drupal::moduleHandler()
      ->invokeAll('geolocation_google_maps_parameters');
    if (!empty($module_parameters['libraries'])) {
      $module_libraries = array_unique($module_parameters['libraries']);
      $form['parameters']['libraries']['module_defined'] = [
        '#prefix' => $this
          ->t('Module defined library requirements - These libraries will be loaded anyway and should not be listed here.'),
        '#theme' => 'item_list',
        '#items' => $module_libraries,
      ];
    }
    $default_libraries = empty($custom_parameters['libraries']) ? [] : $custom_parameters['libraries'];
    $max = max($form_state
      ->get('fields_count'), count($default_libraries), 0);
    $form_state
      ->set('fields_count', $max);

    // Add elements that don't already exist.
    for ($delta = 0; $delta <= $max; $delta++) {
      if (empty($form['parameters']['libraries'][$delta])) {
        $form['parameters']['libraries'][$delta] = [
          '#type' => 'textfield',
          '#title' => $this
            ->t('Library name'),
          '#default_value' => empty($default_libraries[$delta]) ? '' : $default_libraries[$delta],
        ];
      }
    }
    $form['parameters']['libraries']['add'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add library'),
      '#submit' => [
        [
          $this,
          'addLibrariesSubmit',
        ],
      ],
      '#ajax' => [
        'callback' => [
          $this,
          'addLibrariesCallback',
        ],
        'wrapper' => 'geolocation-google-libraries',
        'effect' => 'fade',
      ],
    ];
    $form['parameters']['region'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Google Maps Region - 'region'"),
      '#default_value' => empty($custom_parameters['region']) ?: $custom_parameters['region'],
    ];
    $form['parameters']['language'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Google Maps Localization - 'language'"),
      '#default_value' => empty($custom_parameters['language']) ?: $custom_parameters['language'],
      '#description' => $this
        ->t('See <a href=":google_localization_link">Google Maps API - Localizing the Map</a>.', [
        ':google_localization_link' => 'https://developers.google.com/maps/documentation/javascript/localization',
      ]),
    ];
    $form['parameters']['v'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Google Maps Version - 'v'"),
      '#default_value' => empty($custom_parameters['v']) ?: $custom_parameters['v'],
      '#description' => $this
        ->t('Will default to current experimental. See <a href=":google_version_link">Google Maps API - Versioning</a>.', [
        ':google_version_link' => 'https://developers.google.com/maps/documentation/javascript/versions',
      ]),
    ];
    $form['parameters']['client'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Google Maps Client ID - 'client'"),
      '#default_value' => empty($custom_parameters['client']) ?: $custom_parameters['client'],
      '#description' => $this
        ->t('Attention: setting this option has major usage implications. See <a href=":google_client_id_link">Google Maps Authentication documentation</a>.', [
        ':google_client_id_link' => 'https://developers.google.com/maps/documentation/javascript/get-api-key#client-id',
      ]),
    ];
    $form['parameters']['channel'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Google Maps Channel ID - 'channel'"),
      '#default_value' => empty($custom_parameters['channel']) ?: $custom_parameters['channel'],
      '#description' => $this
        ->t('Channel parameter will be used together with client ID to track usage of your application. See <a href=":google_channel_id_link">Google Maps Premium reports - Channels data </a>.', [
        ':google_channel_id_link' => 'https://developers.google.com/maps/premium/reports/usage-reports#channels',
      ]),
    ];
    $form['use_current_language'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Use current interface language in Google Maps'),
      '#default_value' => $config
        ->get('use_current_language') ? TRUE : FALSE,
      '#description' => $this
        ->t('If a supported language is set by Drupal, it will be handed over to Google Maps. Defaults to language parameter above if set. List of <a href=":google_languages_list">supported languages here</a>.', [
        ':google_languages_list' => 'https://developers.google.com/maps/faq#languagesupport',
      ]),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Ajax submit to add new field.
   */
  public function addLibrariesSubmit(array &$form, FormStateInterface &$form_state) {
    $max = $form_state
      ->get('fields_count') + 1;
    $form_state
      ->set('fields_count', $max);
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * Ajax callback to add new field.
   */
  public function addLibrariesCallback(array &$form, FormStateInterface &$form_state) {
    return $form['parameters']['libraries'];
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->configFactory()
      ->getEditable('geolocation.settings');
    $config
      ->set('google_map_api_key', $form_state
      ->getValue('google_map_api_key'));
    $config
      ->set('google_map_api_server_key', $form_state
      ->getValue('google_map_api_server_key'));
    $config
      ->set('use_current_language', $form_state
      ->getValue('use_current_language'));
    $parameters = $form_state
      ->getValue('parameters');
    unset($parameters['libraries']['add']);
    $parameters['libraries'] = array_unique($parameters['libraries']);
    foreach ($parameters['libraries'] as $key => $library) {
      if (empty($library)) {
        unset($parameters['libraries'][$key]);
      }
    }
    $parameters['libraries'] = array_values($parameters['libraries']);
    $config
      ->set('google_map_custom_url_parameters', $parameters);
    $config
      ->save();

    // Confirmation on form submission.
    drupal_set_message($this
      ->t('The configuration options have been saved.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
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
GeolocationSettings::addLibrariesCallback public function Ajax callback to add new field.
GeolocationSettings::addLibrariesSubmit public function Ajax submit to add new field.
GeolocationSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
GeolocationSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
GeolocationSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
GeolocationSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
GoogleMapsDisplayTrait::$GOOGLEMAPSAPIURL public static property Google maps url with default parameters.
GoogleMapsDisplayTrait::$HYBRID public static property Google map style - Hybrid.
GoogleMapsDisplayTrait::$MAXZOOMLEVEL public static property Google map max zoom level.
GoogleMapsDisplayTrait::$MINZOOMLEVEL public static property Google map min zoom level.
GoogleMapsDisplayTrait::$ROADMAP public static property Google map style - Roadmap.
GoogleMapsDisplayTrait::$SATELLITE public static property Google map style - Satellite.
GoogleMapsDisplayTrait::$TERRAIN public static property Google map style - Terrain.
GoogleMapsDisplayTrait::getGoogleMapDefaultSettings public static function Provide a populated settings array.
GoogleMapsDisplayTrait::getGoogleMapsApiParameters public function Return all module and custom defined parameters.
GoogleMapsDisplayTrait::getGoogleMapsApiUrl public function Return the fully build URL to load Google Maps API.
GoogleMapsDisplayTrait::getGoogleMapsSettings public function Provide settings ready to handover to JS to feed to Google Maps.
GoogleMapsDisplayTrait::getGoogleMapsSettingsForm public function Provide a generic map settings form array.
GoogleMapsDisplayTrait::getGoogleMapsSettingsSummary public function Provide a summary array to use in field formatters.
GoogleMapsDisplayTrait::getMapTypes private function An array of all available map types.
GoogleMapsDisplayTrait::validateGoogleMapsSettingsForm public function Validate the form elements defined above.
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.