CommerceCurrencyResolverSelectForm.php in Commerce Currency Resolver 8
File
src/Form/CommerceCurrencyResolverSelectForm.php
View source
<?php
namespace Drupal\commerce_currency_resolver\Form;
use Drupal\commerce_currency_resolver\CurrencyHelperInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class CommerceCurrencyResolverSelectForm extends FormBase {
protected $requestStack;
protected $currencyHelper;
protected $time;
public function __construct(RequestStack $request_stack, CurrencyHelperInterface $currency_helper, TimeInterface $time) {
$this->requestStack = $request_stack;
$this->currencyHelper = $currency_helper;
$this->time = $time;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('request_stack'), $container
->get('commerce_currency_resolver.currency_helper'), $container
->get('datetime.time'));
}
public function getFormId() {
return 'commerce_currency_resolver_select_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$request = $this->requestStack
->getCurrentRequest();
$active_currencies = $this->currencyHelper
->getCurrencies();
$cookies = $request->cookies;
$cookie_name = $this->currencyHelper
->getCookieName();
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'),
];
$form['#cache']['contexts'][] = 'currency_resolver';
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$selected_currency = $form_state
->getValue('currency');
setrawcookie($this->currencyHelper
->getCookieName(), rawurlencode($selected_currency), $this->time
->getRequestTime() + 86400, '/');
}
}