我必須在自己的購物車中添加一些自定義金額的訂單項。 商業產品保存的價格= 0,我的模塊計算價格並將訂單項添加到購物車/訂單,但我不明白如何以編程方式設置價格。Drupal Commerce Line Items:改變價格?
我已閱讀使用規則,但我需要我的模塊能夠設置/更改價格,,而無需調用規則。我嘗試改變使用commerce_product_line_item_new()創建的行項目,但沒有任何內容,當訂單項進入購物車時始終具有原始產品價格(在我的情況下爲0) 。
如何以編程方式更改訂單項價格?
到目前爲止我的代碼看起來像:
// For debugging, this function is called by hook_menu()
function mymodule_test($product_id)
{
global $user;
$user = user_load($user->uid);
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new(
$product,
1,
0,
array(
),
'cover'
);
$line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $line_item);
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
$line_item_wrapper->commerce_unit_price->value(),
'base_price',
array(
'amount' => 1234,
'currency_code' => 'EUR',
'data' => array(),
),
TRUE
);
$insert_line_item = commerce_cart_product_add($user->uid, $line_item_wrapper->value(), FALSE);
return 'done';
}
奇怪的是,我tryed適應commerce_line_item_unit_price_amount()在商業/模塊/ LINE_ITEM/commerce_line_item.rules.inc發現的代碼,但是這測試:
<?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);
?>
仍然失敗,line_item進入購物車,但與參考產品的原始價格。
有什麼想法?
你不保存您的包裝......這可能是問題(即'$ line_item_wrapper->保存();') – Clive
@Clive我想我也嘗試過,但讓我再試一次,以防萬一 – Strae
哦,你還需要保存'$ order_wrapper'(當我做某事的時候,類似幾個月回來) – Clive