You are here

public function CommerceCurrencyResolverSelectForm::buildForm in Commerce Currency Resolver 8

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

src/Form/CommerceCurrencyResolverSelectForm.php, line 70

Class

CommerceCurrencyResolverSelectForm
Class CommerceCurrencyResolverSelectForm.

Namespace

Drupal\commerce_currency_resolver\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $request = $this->requestStack
    ->getCurrentRequest();

  // Get all active currencies.
  $active_currencies = $this->currencyHelper
    ->getCurrencies();

  // Get cookies.
  $cookies = $request->cookies;
  $cookie_name = $this->currencyHelper
    ->getCookieName();

  // Get values from cookie.
  if ($cookies
    ->has($cookie_name) && isset($active_currencies[$cookies
    ->get($cookie_name)])) {
    $selected_currency = $cookies
      ->get($cookie_name);
  }
  else {
    $selected_currency = $this->currencyHelper
      ->defaultCurrencyCode();
  }
  $form['currency'] = [
    '#type' => 'select',
    '#options' => $active_currencies,
    '#default_value' => $selected_currency,
    '#attributes' => [
      'onChange' => [
        'this.form.submit()',
      ],
    ],
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Submit'),
  ];

  // Add currency cache context.
  $form['#cache']['contexts'][] = 'currency_resolver';
  return $form;
}