You are here

function payment_form_process_line_item_validate in Payment 7

Implements form validate callback for a payment_line_item element.

1 string reference to 'payment_form_process_line_item_validate'
payment_element_info in ./payment.module
Implements hook_element_info().

File

./payment.ui.inc, line 829
The Payment user interface.

Code

function payment_form_process_line_item_validate(array $element, array &$form_state) {
  $values = drupal_array_get_nested_value($form_state['values'], $element['#parents']);

  // Don't let the submit button's value be validated.
  unset($values['add_more']);
  $line_items = array();
  foreach ($values as $container => $line_item_data) {

    // All this line item's elements are empty, so there's nothing to validate.
    if (reset($line_item_data) == '' && count(array_unique($line_item_data)) == 1) {
      break;
    }
    else {

      // Keep track
      $errors = array_fill_keys(array_keys($element['#value']), FALSE);
      foreach ($line_item_data as $property => $value) {
        if (!strlen($value)) {
          form_error($element[$container][$property], t('%title is required, or leave all fields for this line item empty.', array(
            '%title' => $element[$container][$property]['#title'],
          )));
        }
      }
    }

    // Validate quantity.
    if (!is_numeric($line_item_data['quantity'])) {
      form_error($element[$container]['quantity'], t('Quantity should be a number.'));
    }

    // Validate tax rate.
    $tax_rate = str_replace(',', '.', $line_item_data['tax_rate']);
    if (!is_numeric($tax_rate) || $tax_rate < 0) {
      form_error($element, t('Tax rate must be a positive percentage.'));
    }
    else {
      $line_item_data['tax_rate'] = $tax_rate / 100;
    }

    // Convert the raw input to a PaymentLineItem object.
    $line_item_data['amount'] = (double) $line_item_data['amount'];
    $line_item_data['quantity'] = (double) $line_item_data['quantity'];
    $line_item_data['tax_rate'] = (double) $line_item_data['tax_rate'];
    $line_items[] = new PaymentLineItem($line_item_data);
  }
  form_set_value($element, $line_items, $form_state);
}