3

I am using Drupal Commerce. Now I have to alter the product price programmatically. After search on google and here, I found some people did it: Alter cart unit price and total amount

Then I made a test by using hook_commerce_cart_order_refresh(). Here is my code:

function mymodule_commerce_cart_order_refresh($order_wrapper){
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
        $line_item = $line_item_wrapper->value();
        $qty = $line_item->quantity;
        $line_item->commerce_unit_price['und']['0']['amount']=100;
        $line_item->commerce_total['und']['0']['amount']=$qty*100;
        commerce_line_item_save($line_item);
    }
}

It changed the cart and order line item unit price and line item totoal amont. But the order total will not changed. Still calculated on the old price.

I also notice somebody have the same question:Order Total not updating after I change the line item price , but I don't know that answer how it works. It said using following code:

The solution was to use commerce_price_add_component()

$line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
    $line_item_wrapper->commerce_unit_price->value(),
    'base_price',
    array(
            'amount' => $booking_price,
            'currency_code' => 'AUD',
            'data' => array(),
    ),
    TRUE
);

But I don't know where to use the above code, put in a hook?

Is some one can give me a idea?

2

I'v found the way. Put answer here:

function mymodule_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    $line_item->commerce_unit_price['und']['0']['amount']=110;
    $line_item->commerce_unit_price['und']['0']['data']['components']['0']['price']        ['amount']=110;
}

Because the commerce_order_calculate_total() is based on components, so if you only changed the commerce_unit_price amount is not enough. Must change data also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.