function commerce_tax_field_attach_load in Commerce Core 7
Implements hook_field_attach_load().
File
- modules/
tax/ commerce_tax.module, line 453 - Defines tax rates and Rules integration for configuring tax rules for applicability and display.
Code
function commerce_tax_field_attach_load($entity_type, $entities, $age, $options) {
// If product entities are being loaded...
if ($entity_type == 'commerce_product') {
// Loop over all the products looking for prices needing tax calculation.
foreach ($entities as $product) {
// Examine every field instance attached to this product's bundle.
foreach (field_info_instances('commerce_product', $product->type) as $field_name => $instance) {
// Load the instance's field data.
$field = field_info_field($instance['field_name']);
// If the instance is of a price field...
if ($field['type'] == 'commerce_price' && !empty($product->{$field_name})) {
// Check to see if the product has specified an included tax.
foreach ($product->{$field_name} as $langcode => $items) {
foreach ($items as $delta => $item) {
// If it specifies a tax and we can load it...
if (!empty($item['data']['include_tax']) && ($tax_rate = commerce_tax_rate_load($item['data']['include_tax']))) {
// Clean the price's components array, as we must start with a
// blank slate to rebuild the components for inclusive taxes.
$item['data']['components'] = array();
// Reverse apply the tax.
$tax_amount = $item['amount'] - $item['amount'] / (1 + $tax_rate['rate']);
$tax_amount = commerce_tax_rate_round_amount($tax_rate, $tax_amount);
// Add a base price to the data array.
$component = array(
'amount' => $item['amount'] - $tax_amount,
'currency_code' => $item['currency_code'],
'data' => array(),
);
$item['data'] = commerce_price_component_add($item, 'base_price', $component, TRUE);
// Add the tax to the data array.
$component['amount'] = $tax_amount;
$component['data']['tax_rate'] = $tax_rate;
$item['data'] = commerce_price_component_add($item, $tax_rate['price_component'], $component, TRUE);
// Set the new item on the product entity.
$product->{$field_name}[$langcode][$delta] = $item;
}
}
}
}
}
}
}
}