You are here

class CommerceCurrencyResolverForm in Commerce Currency Resolver 8

Class CommerceCurrencyResolverForm.

@package Drupal\commerce_currency_resolver\Form

Hierarchy

Expanded class hierarchy of CommerceCurrencyResolverForm

1 string reference to 'CommerceCurrencyResolverForm'
commerce_currency_resolver.routing.yml in ./commerce_currency_resolver.routing.yml
commerce_currency_resolver.routing.yml

File

src/Form/CommerceCurrencyResolverForm.php, line 16

Namespace

Drupal\commerce_currency_resolver\Form
View source
class CommerceCurrencyResolverForm extends ConfigFormBase {

  /**
   * Helper service.
   *
   * @var \Drupal\commerce_currency_resolver\CurrencyHelperInterface
   */
  protected $currencyHelper;

  /**
   * CommerceCurrencyResolverForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Drupal config.
   * @param \Drupal\commerce_currency_resolver\CurrencyHelperInterface $currency_helper
   *   Generic helper.
   */
  public function __construct(ConfigFactoryInterface $config_factory, CurrencyHelperInterface $currency_helper) {
    parent::__construct($config_factory);
    $this->currencyHelper = $currency_helper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('commerce_currency_resolver.currency_helper'));
  }

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

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

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

    // Get current settings.
    $config = $this
      ->config('commerce_currency_resolver.settings');
    $form['currency_mapping'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Currency mapping'),
      '#description' => $this
        ->t('Select how currency is mapped in the system. By country, language.'),
      '#options' => $this
        ->getAvailableMapping(),
      '#default_value' => $config
        ->get('currency_mapping'),
      '#required' => TRUE,
    ];
    $geo_modules = $this->currencyHelper
      ->getGeoModules();
    if (!empty($geo_modules) && $config
      ->get('currency_mapping') === 'geo') {
      $form['currency_geo'] = [
        '#type' => 'radios',
        '#title' => $this
          ->t('Location module'),
        '#description' => $this
          ->t('Select which module is used for geolocation services'),
        '#options' => $geo_modules,
        '#default_value' => $config
          ->get('currency_geo'),
        '#required' => TRUE,
      ];
    }
    $form['currency_source'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Currency source'),
      '#description' => $this
        ->t('Select how currency is added and calculated. To avoid possible errors, "Combo mode" is best option. If field for currency does not exist, it will fallback to automatic conversion for this specific currency'),
      '#options' => [
        'auto' => $this
          ->t('Automatic conversion'),
        'field' => $this
          ->t('Price field per currency'),
        'combo' => $this
          ->t('Combo mode'),
      ],
      '#default_value' => $config
        ->get('currency_source'),
      '#required' => TRUE,
    ];
    $exchange_rates = $this->currencyHelper
      ->getExchangeRatesProviders();
    $form['currency_exchange_rates'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Exchange rate API'),
      '#description' => $this
        ->t('Select which external service you want to use for calculating exchange rates between currencies'),
      '#options' => $exchange_rates,
      '#default_value' => $config
        ->get('currency_exchange_rates'),
      '#required' => TRUE,
    ];

    // If there is no exchanger plugin.
    if (empty($exchange_rates)) {
      $form['currency_exchange_rates']['#field_suffix'] = $this
        ->t('Please add at least one exchange rate provider under Exchange rates');
      $form['submit']['#disabled'] = TRUE;
    }
    $form['currency_default'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default currency'),
      '#description' => $this
        ->t('Select currency which you consider default - as fallback if all resolvers fails, and upon exchange rates should be calculated'),
      '#options' => $this->currencyHelper
        ->getCurrencies(),
      '#default_value' => $config
        ->get('currency_default'),
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * Get all available option where currency could be mapped.
   *
   * @return array
   *   Array of options available for currency mapping.
   */
  protected function getAvailableMapping() {
    $mapping = [];

    // Default store.
    $mapping['store'] = $this
      ->t('Store (default Commerce 2 behavior)');
    $mapping['cookie'] = $this
      ->t('Cookie (currency block selector)');

    // Check if exist geo based modules.
    // We support for now two of them.
    if (!empty($this->currencyHelper
      ->getGeoModules())) {
      $mapping['geo'] = $this
        ->t('By Country');
    }

    // Check if the site is multilingual.
    if (count($this->currencyHelper
      ->getLanguages()) > 1) {
      $mapping['lang'] = $this
        ->t('By Language');
    }
    return $mapping;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('commerce_currency_resolver.settings');

    // Set values.
    $config
      ->set('currency_mapping', $form_state
      ->getValue('currency_mapping'))
      ->set('currency_geo', $form_state
      ->getValue('currency_geo'))
      ->set('currency_source', $form_state
      ->getValue('currency_source'))
      ->set('currency_default', $form_state
      ->getValue('currency_default'))
      ->set('currency_exchange_rates', $form_state
      ->getValue('currency_exchange_rates'))
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CommerceCurrencyResolverForm::$currencyHelper protected property Helper service.
CommerceCurrencyResolverForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
CommerceCurrencyResolverForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
CommerceCurrencyResolverForm::getAvailableMapping protected function Get all available option where currency could be mapped.
CommerceCurrencyResolverForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
CommerceCurrencyResolverForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CommerceCurrencyResolverForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
CommerceCurrencyResolverForm::__construct public function CommerceCurrencyResolverForm constructor. Overrides ConfigFormBase::__construct
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.
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.