You are here

function _commerce_price_rules_data_ui_element_validate in Commerce Core 7

Validates data entered via a price input form in a Rules condition or action.

1 string reference to '_commerce_price_rules_data_ui_element_validate'
RulesDataUICommercePrice::inputForm in modules/price/commerce_price.rules.inc
Constructs the direct input form.

File

modules/price/commerce_price.module, line 1123
Defines the Price field with widgets and formatters used to add prices with currency codes to various Commerce entities.

Code

function _commerce_price_rules_data_ui_element_validate($element, &$form_state, $form) {
  $value = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
  $value['amount'] = trim($value['amount']);
  $currency = commerce_currency_load($value['currency_code']);

  // Required elements don't work on these input forms, so instead catch
  // an empty value here and require a numeric amount.
  if ($value['amount'] == '') {
    form_error($element, t('A numeric amount is required for setting and comparing against price field data.'));
  }

  // Only convert price amount to major units if we have a numeric value,
  // otherwise throw an error.
  if (is_numeric($value['amount'])) {

    // Ensure price amount is formatted correctly in major units according to the
    // currency code.
    $minor_unit_amount = number_format($value['amount'], $currency['decimals'], '.', '');

    // Now that the minor unit amount expected by the currency, we can safely
    // convert back to major units for storage.
    $value['amount'] = commerce_currency_decimal_to_amount($minor_unit_amount, $value['currency_code']);
    form_set_value($element, $value, $form_state);
  }
  else {
    form_error($element, t('Price amount must be numeric.'));
  }
}