You are here

public function CommerceCurrencyResolverAmountTrait::buildConfigurationForm in Commerce Currency Resolver 8

File

src/Plugin/Commerce/CommerceCurrencyResolverAmountTrait.php, line 23

Class

CommerceCurrencyResolverAmountTrait
Provides common configuration for fixed amount off offers.

Namespace

Drupal\commerce_currency_resolver\Plugin\Commerce

Code

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildConfigurationForm($form, $form_state);

  // Get default currency.
  $defaultCurrency = \Drupal::service('commerce_currency_resolver.currency_helper')
    ->fallbackCurrencyCode();

  // If we handle commerce conditions and promotions.
  if (isset($form['amount']) && empty($form['amount']['#default_value'])) {
    $form['amount']['#default_value'] = [
      'number' => '',
      'currency_code' => $defaultCurrency,
    ];
  }
  $form['fields'] = [
    '#type' => 'details',
    '#open' => FALSE,
    '#description' => $this
      ->t('If you leave amounts per currency empty, they should be auto-calculated to avoid mismatch in currency on orders.'),
    '#title' => $this
      ->t('Amount per currency'),
    '#tree' => TRUE,
  ];

  // Get all enabled currencies.
  $enabledCurrencies = \Drupal::service('commerce_currency_resolver.currency_helper')
    ->getCurrencies();
  foreach ($enabledCurrencies as $key => $currency) {
    $amount_key = $this->configuration['fields'][$key] ?? NULL;

    // An #ajax bug can cause $amount_key to be incomplete.
    if (isset($amount_key) && !isset($amount_key['number'], $amount_key['currency_code'])) {
      $amount_key = NULL;
    }
    $form['fields'][$key] = [
      '#type' => 'commerce_price',
      '#title' => $this
        ->t('Amount'),
      '#default_value' => $amount_key,
      '#required' => FALSE,
      '#available_currencies' => [
        $key,
      ],
    ];
  }
  return $form;
}