You are here

public static function PriceTableDefaultWidget::validateElement in Commerce Price Table 8

Form validation handler for widget elements.

File

src/Plugin/Field/FieldWidget/PriceTableDefaultWidget.php, line 67

Class

PriceTableDefaultWidget
Plugin implementation of the 'commerce_price_table' widget.

Namespace

Drupal\commerce_price_table\Plugin\Field\FieldWidget

Code

public static function validateElement(array $element, FormStateInterface $form_state) {
  if ($element['amount']['#value'] !== '') {

    // Ensure the price is numeric.
    if (!is_numeric($element['amount']['#value'])) {
      $form_state
        ->setError($element['amount'], t('%title: you must enter a numeric value for the price amount.', [
        '%title' => $element['amount']['#title'],
      ]));
    }
    else {
      $form_state
        ->setValueForElement($element['amount'], $element['amount']['#value']);
    }

    // Ensure the quantity fields are valid values.
    if (!isset($element['min_qty']['#value']) || $element['min_qty']['#value'] == '' || !ctype_digit($element['min_qty']['#value']) || $element['min_qty']['#value'] < 1) {
      $form_state
        ->setError($element['min_qty'], t('%name: Minimum quantity values must be integers greater than 0.', [
        '%name' => $element['min_qty']['#title'],
      ]));
    }
    else {
      $form_state
        ->setValueForElement($element['min_qty'], $element['min_qty']['#value']);
    }
    if (!isset($element['max_qty']['#value']) || $element['max_qty']['#value'] == '' || !ctype_digit($element['max_qty']['#value']) && $element['max_qty']['#value'] != -1 || $element['max_qty']['#value'] < -1 || $element['max_qty']['#value'] == 0) {
      $form_state
        ->setError($element['max_qty'], t('%name: Maximum quantity values must be integers greater than 0 or -1 for unlimited.', [
        '%name' => $element['max_qty']['#title'],
      ]));
    }
    if ($element['max_qty']['#value'] < $element['min_qty']['#value'] && $element['max_qty']['#value'] != -1) {
      $form_state
        ->setError($element['max_qty'], t('%name: Maximum quantity values must be higher than their related minimum quantity values.', [
        '%name' => $element['max_qty']['#title'],
      ]));
    }
    else {
      $form_state
        ->setValueForElement($element['max_qty'], $element['max_qty']['#value']);
    }
  }
}