2
Answers
Vote up!
0
Vote down!

Line Items: alter the price?

I have to add to my cart some line items with a custom amount.
The commerce product is saved with price = 0, and my module compute the price and add the line item to the cart/order, but i dont understand how to set programmatically the price (same problem of this post)

I've tryed with an entity wrapper, i tryed to alter the line item created with commerce_product_line_item_new(), but nothing, when the line item gets into the cart always has the original product price (in my case, 0).

How to alter a line item price programmatically?

strae
Asked by: strae
on November 16, 2012

2 Answers

Vote up!
0
Vote down!

The strange thing, is that I tryed to adapt the code of commerce_line_item_unit_price_amount() found in commerce/modules/line_item/commerce_line_item.rules.inc, so my code liiks like:

<?php
   
global $user;
   
$product = commerce_product_load(4); // my commerce product for test
   
   
$line_item = commerce_product_line_item_new(
       
$product,
       
1,
       
0,
        array(
        ),
       
'cover' // I do have this line_items type
   
);
   
   
// manually set amount and component name
   
$amount = 1234;
   
$component_name = 'base_price'; // tryed with discount, nothing change
   
   
$wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
   
$unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

   
// Calculate the updated amount and create a price array representing the
    // difference between it and the current amount.
   
$current_amount = $unit_price['amount'];
   
$updated_amount = commerce_round(COMMERCE_ROUND_HALF_UP, $amount);

   
$difference = array(
       
'amount' => $updated_amount - $current_amount,
       
'currency_code' => $unit_price['currency_code'],
       
'data' => array(),
    );

   
// Set the amount of the unit price and add the difference as a component.
   
$wrapper->commerce_unit_price->amount = $updated_amount;

   
$wrapper->commerce_unit_price->data = commerce_price_component_add(
       
$wrapper->commerce_unit_price->value(),
       
$component_name,
       
$difference,
       
TRUE
   
);
   
   
$insert_line_item = commerce_cart_product_add($user->uid, $line_item, FALSE);
?>
strae
Answer by: strae
Posted: Nov 16, 2012