You are here

public function BuyXGetY::validateConfigurationForm in Commerce Core 8.2

Form validation handler.

Parameters

array $form: An associative array containing the structure of the plugin form as built by static::buildConfigurationForm().

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form. Calling code should pass on a subform state created through \Drupal\Core\Form\SubformState::createForSubform().

Overrides PromotionOfferBase::validateConfigurationForm

File

modules/promotion/src/Plugin/Commerce/PromotionOffer/BuyXGetY.php, line 279

Class

BuyXGetY
Provides the "Buy X Get Y" offer for orders.

Namespace

Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer

Code

public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  parent::validateConfigurationForm($form, $form_state);
  $values = $form_state
    ->getValue($form['#parents']);
  if ($values['offer']['type'] == 'percentage' && empty($values['offer']['percentage'])) {
    $form_state
      ->setError($form, $this
      ->t('Percentage must be a positive number.'));
  }
  if ($values['get']['auto_add']) {

    // Ensure that at least one compatible condition enabled.
    $valid_condition_ids = array_keys($this
      ->getPurchasableEntityConditions());
    $has_valid_condition = FALSE;
    foreach ($values['get']['conditions']['products'] as $condition_id => $condition_values) {
      if (in_array($condition_id, $valid_condition_ids) && (bool) $condition_values['enable']) {
        $has_valid_condition = TRUE;
        break;
      }
    }

    // We can't automatically add the "get" product if no valid conditions are
    // selected.
    if (!$has_valid_condition) {
      $values['get']['auto_add'] = FALSE;
      $form_state
        ->setValue($form['#parents'], $values);
      return;
    }

    // Ensure that the offer is a 100% discount.
    if ($values['offer']['type'] === 'fixed_amount' || $values['offer']['type'] === 'percentage' && $values['offer']['percentage'] != '100') {
      $form_state
        ->setError($form['offer'], $this
        ->t('The "auto-add" offer can only be enabled for fully discounted products (i.e with a 100% discount).'));
    }
  }
}