You are here

class SettingsForm in Leaflet More Maps 8

Same name and namespace in other branches
  1. 2.1.x src/Form/SettingsForm.php \Drupal\leaflet_more_maps\Form\SettingsForm

Form to enter global settings and to assemble custom maps from overlays.

Hierarchy

Expanded class hierarchy of SettingsForm

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

File

src/Form/SettingsForm.php, line 11

Namespace

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    global $base_url;
    $config = $this->configFactory
      ->get('leaflet_more_maps.settings');
    $form['global_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Map provider API keys/access tokens'),
      '#description' => $this
        ->t("After you've entered and saved keys for the map provider(s) relevant to you, visit the <a href='@showcase_page' target='_showcase'>map showcase page</a> to check they work.", [
        '@showcase_page' => $base_url . '/admin/config/system/leaflet-more-maps/demo',
      ]),
      '#open' => TRUE,
    ];
    if (!\Drupal::moduleHandler()
      ->moduleExists('leaflet_demo')) {
      $form['global_settings']['#description'] .= '<br/>' . $this
        ->t('The Leaflet Demo module is currently not enabled. To see the map showcase page, please <a href="@extend" target="_extend">enable Leaflet Demo</a>.', [
        '@extend' => $base_url . '/admin/modules',
      ]);
    }
    $form['global_settings']['thunderforest_api_key'] = [
      '#type' => 'textfield',
      '#size' => 31,
      '#title' => t('OSM Thunderforest API key'),
      '#default_value' => $config
        ->get('thunderforest_api_key', ''),
      '#description' => $this
        ->t('If you use a <a href="@thunderforest" target="_thunderforest_maps">Thunderforest</a> map, please <a href="@api_key" target="_api_key">obtain an API key</a> and paste it above.', [
        '@thunderforest' => 'https://www.thunderforest.com/maps',
        '@api_key' => 'http://www.thunderforest.com/docs/apikeys/',
      ]),
    ];
    $form['global_settings']['here_api_key'] = [
      '#type' => 'textfield',
      '#size' => 43,
      '#title' => $this
        ->t('HERE API key'),
      '#default_value' => $config
        ->get('here_api_key', ''),
      '#description' => $this
        ->t('If you use a <a href="@here_maps" target="_here_maps">HERE</a> map, please sign up for an account, <a href="@api_key" target="_api_key">create an API key</a> and paste it above.', [
        '@here_maps' => 'https://here.com',
        '@api_key' => 'https://developer.here.com',
      ]),
    ];
    $form['global_settings']['mapbox_access_token'] = [
      '#type' => 'textfield',
      '#size' => 83,
      '#title' => $this
        ->t('mapbox access token'),
      '#default_value' => $config
        ->get('mapbox_access_token', ''),
      '#description' => $this
        ->t('If you use a <a href="@mapbox" target="_mapbox_maps">mapbox</a> map, please create an account, <a href="@access_token target="_access_token">generate an access token</a> and paste it above.', [
        '@mapbox' => 'https://www.mapbox.com',
        '@access_token' => 'https://docs.mapbox.com/help/glossary/access-token',
      ]),
    ];
    $map_info = [];
    _leaflet_more_maps_assemble_default_map_info($map_info);
    $all_layer_keys = [];
    foreach ($map_info as $map_key => $map) {
      foreach ($map['layers'] as $layer_key => $layer) {

        // Unique.
        $all_layer_keys["{$map_key} {$layer_key}"] = "{$map_key} {$layer_key}";
      }
    }
    $custom_map_layers = $config
      ->get('leaflet_more_maps_custom_maps', []);
    if (empty($custom_map_layers)) {
      for ($i = 1; $i <= LEAFLET_MORE_MAPS_NO_CUSTOM_MAPS; $i++) {
        $custom_map_layers[$i] = [
          'map-key' => '',
          'layer-keys' => [],
          'reverse-order' => FALSE,
        ];
      }
    }
    for ($i = 1; $i <= LEAFLET_MORE_MAPS_NO_CUSTOM_MAPS; $i++) {
      $form['map'][$i] = [
        '#type' => 'details',
        '#open' => $i <= 1,
        '#title' => $this
          ->t('Custom map #@number layer selection', [
          '@number' => $i,
        ]),
      ];
      $form['map'][$i]['map-key'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Name of custom map #@number in the administrative UI', [
          '@number' => $i,
        ]),
        '#default_value' => $custom_map_layers[$i]['map-key'],
        '#description' => $this
          ->t('Use a blank field to remove this layer configuration from the set of selectable maps.'),
      ];
      $form['map'][$i]['layer-keys'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Select one or more layers to be included in this map.'),
        '#options' => $all_layer_keys,
        '#default_value' => $custom_map_layers[$i]['layer-keys'],
        '#description' => $this
          ->t('If you select two or more layers, these will be selectable via radio buttons in the layer switcher on your map.'),
      ];
      $form['map'][$i]['reverse-order'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Reverse order in layer switcher'),
        '#default_value' => $custom_map_layers[$i]['reverse-order'],
        '#description' => $this
          ->t('The last layer in the switcher will be the default.'),
      ];
      $form['map'][$i]['map-key']['#parents'] = [
        'map',
        $i,
        'map-key',
      ];
      $form['map'][$i]['layer-keys']['#parents'] = [
        'map',
        $i,
        'layer-keys',
      ];
      $form['map'][$i]['reverse-order']['#parents'] = [
        'map',
        $i,
        'reverse-order',
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $custom_maps = $form_state
      ->getValue('map');

    // Clear out the unticked boxes before saving the form.
    foreach ($custom_maps as $i => $custom_map) {
      $custom_map['layer-keys'] = array_filter($custom_map['layer-keys']);
      if (empty($custom_map['map_key']) || empty($custom_map['layer_keys'])) {
        unset($custom_maps[$i]);
      }
    }
    $this
      ->config('leaflet_more_maps.settings')
      ->set('thunderforest_api_key', $form_state
      ->getValue('thunderforest_api_key'))
      ->set('mapbox_access_token', $form_state
      ->getValue('mapbox_access_token'))
      ->set('here_api_key', $form_state
      ->getValue('here_api_key'))
      ->set('leaflet_more_maps_custom_maps', $custom_maps)
      ->save();
    parent::submitForm($form, $form_state);

    // @todo Need to refresh config cache.
  }

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

}

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
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::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
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
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.