map_route_planner-1.0.0-alpha4/src/Form/MapRoutePlannerSettingsForm.php

src/Form/MapRoutePlannerSettingsForm.php
<?php

namespace Drupal\map_route_planner\Form;

use Drupal\Core\Asset\LibraryDiscovery;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\map_route_planner\Factory\GoogleMapsFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure Map route planner settings for this site.
 */
class MapRoutePlannerSettingsForm extends ConfigFormBase {
  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Discovers available asset libraries in Drupal.
   *
   * @var \Drupal\Core\Asset\LibraryDiscovery
   */
  protected $library;

  /**
   * The Google Maps Factory.
   *
   * @var \Drupal\map_route_planner\Factory\GoogleMapsFactory
   */
  protected $googleMapsFactory;

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Asset\LibraryDiscovery $library
   *   Discovers available asset libraries in Drupal.
   * @param \Drupal\map_route_planner\Factory\GoogleMapsFactory $google_maps_factory
   *   The Google Maps Factory.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    EntityTypeManagerInterface $entity_type_manager,
    LibraryDiscovery $library,
    GoogleMapsFactory $google_maps_factory
  ) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->library = $library;
    $this->googleMapsFactory = $google_maps_factory;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['authentification'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Authentification'),
    ];
    $form['authentification']['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('API Key'),

      '#default_value' => $this->config('map_route_planner.settings')->get('authentification.api_key'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    if ($this->isFieldValueChanged('authentification.api_key', $form_state)) {

      $request_response = $this->googleMapsFactory->getGeocoding(
        ['address' => '32 rue de Cambrai, 75019, Paris'],
        $form_state->getValue('api_key')
      );
      if (is_null($request_response)) {
        $form_state->setErrorByName(
          'api_key',
          $this->t('The API Key is not correct. The test request failed.')
        );
      }
      elseif(
        !empty($place_id = $request_response['place_id']) &&
        'ChIJsy-MTM1t5kcRzCCfil10m6M' === $place_id
      ) {
        $this->messenger()->addStatus(
          $this->t(
            'The API Key is correct. The test request performed with success.'
          )
        );
      }
    }

    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->isFieldValueChanged('authentification.api_key', $form_state)) {
      // Save the API key.
      $this->config('map_route_planner.settings')
        ->set('authentification.api_key', $form_state->getValue('api_key'))
        ->save();

      // Clear libraries cache.
      $this->library->clearCachedDefinitions();
    }

    parent::submitForm($form, $form_state);
  }

  /**
   * Check if a field value changed.
   *
   * @param string $field_name_key
   *   The field name key.
   * @param FormStateInterface $form_state
   *   Form state object.
   *
   * @return bool
   *   Return the response.
   */
  public function isFieldValueChanged(
    string $field_name_key, FormStateInterface $form_state
  ) {
    $field_form_key = end(
      explode('.', $field_name_key)
    );
    if (!empty($field_value = $form_state->getValue($field_form_key))) {
      $config_value = $this->config('map_route_planner.settings')
        ->get($field_name_key);
      if ($field_value != $config_value) {
        return TRUE;
      }
    }
    return FALSE;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc