Finding information about getting the tax from Drupal Commerce 3 Orders / Oder Items programmatically, was quite difficult. So I decided to write a short Blog entry and snippet on the topic.
The key information here is, that tax
is an Adjustment type and based on the EntityAdjustableInterface
:
/**
* Defines an interface for objects that contain adjustments.
*
* Adjustments store promotions, taxes, fees, shipping costs.
* They can be calculated on the order level (based on the order subtotal),
* or on the order item level (based on the order item total).
*
* if $order_item->usesLegacyAdjustments() is true, the order item adjustments
* were calculated based on the order item unit price, which was the default
* logic prior to Commerce 2.8, changed in #2980713.
*
* Adjustments are always displayed in the order total summary, below
* the subtotal. They are not shown as a part of the order item prices.
* To get the order item total price with adjustments included, use
* $order_item->getAdjustedTotalPrice().
*
* @see \Drupal\commerce_order\Entity\OrderInterfaceEntity
* @see \Drupal\commerce_order\Entity\OrderItemInterfaceEntity
*/
interface EntityAdjustableInterface extends EntityInterface {
...
}
It's important to read the information about the different levels: Order and OrderItem!
Setting, adding, removing adjustments is typically a (complicated) module job, for example in the commerce submodules commerce_promition, commerce_tax and contrib module like commerce_giftcard.
What we want is getAdjustments()
:
/**
* Gets the adjustments.
*
* @param string[] $adjustment_types
* The adjustment types to include.
* Examples: fee, promotion, tax. Defaults to all adjustment types.
*
* @return \Drupal\commerce_order\Adjustment[]
* The adjustments.
*/
public function getAdjustments(array $adjustment_types = []);
And as you can see in the documentation, you can filter by adjustment type, so we use:
// For the order:
$order->getAdjustments(['tax'])
// For order items:
$order->getAdjustments(['tax'])
to get the applied tax(es).
This returns an array with Objects of type \Drupal\commerce_order\
Adjustment like this:
array:1 [▼ 0 => Drupal\commerce_order\Adjustment {#6494 ▼ #type: "tax" #label: "MwSt." #amount: Drupal\commerce_price\Price {#6495 ▼ #number: "3.40" #currencyCode: "EUR" } #percentage: "0.19" #sourceId: "european_union_vat|de|standard" #included: true #locked: false } ]
And there you go - here are your absolute and percentage taxes applied!