You are here

function commerce_gc_validate_order_form_giftcard_transactions in Commerce GC 7

1 string reference to 'commerce_gc_validate_order_form_giftcard_transactions'
commerce_gc_form_commerce_order_ui_order_form_alter in ./commerce_gc.module

File

./commerce_gc.module, line 868
Provides Giftcard coupon bundle, Giftcard Transaction entity and basic user interface elements.

Code

function commerce_gc_validate_order_form_giftcard_transactions(&$form, &$form_state) {

  // Check if this using an inline entity form
  if (isset($form_state['inline_entity_form'])) {

    // Since line items are locked, we can rely on first entry
    $ief = reset($form_state['inline_entity_form']);
    $line_items = $ief['entities'];
  }
  else {
    $order = $form_state['commerce_order'];
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $order_wrapper->commerce_line_items;
  }

  // Make sure that any giftcard line items do not exceed the current balance on
  // their respective coupon entities.
  foreach ($line_items as $line_item_wrapper) {

    // Double check we have a wrapper
    if (!$line_item_wrapper instanceof EntityMetadataWrapper) {
      $line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $line_item_wrapper['entity']);
    }
    if ($line_item_wrapper
      ->value() && $line_item_wrapper->type
      ->value() == 'giftcard_use') {
      $unit_amount = $line_item_wrapper->commerce_unit_price->amount
        ->value();
      $coupon = $line_item_wrapper->commerce_giftcard
        ->value();

      // Giftcard use unit prices must be negative.
      if ($unit_amount === 0) {
        form_set_error('', t('The line item amount for giftcard @code cannot be zero. Try removing it instead.', array(
          '@code' => $coupon->code,
        )));
      }
      if ($unit_amount > 0) {
        form_set_error('', t('The line item amount for giftcard @code must be negative.', array(
          '@code' => $coupon->code,
        )));
      }
    }
  }
}