【发布时间】:2012-11-21 11:10:31
【问题描述】:
我必须将一些自定义金额的订单项添加到我的购物车中。 商务产品以 price = 0 保存,我的模块计算价格并将订单项添加到购物车/订单,但我不明白如何以编程方式设置价格。
我已阅读有关使用规则的信息,但我需要我的模块能够设置/更改价格,无需调用规则。
我尝试过使用实体包装器,我尝试更改使用 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';
}
奇怪的是,我试图修改 commerce/modules/line_item/commerce_line_item.rules.inc 中的 commerce_line_item_unit_price_amount() 的代码,但是这个测试:
<?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->save();) -
@Clive 我想我也试过了,但让我再试一次以防万一
-
哦,你还需要保存
$order_wrapper(几个月前我在做类似的事情时得到了我) -
@Clive 尝试过,仍然无法正常工作。我在之前(以及之后,以防万一)
commerce_cart_product_add添加了$line_item_wrapper->save(); $order_wrapper->save();,但没有任何改变...我没有收到任何错误,行项目进入购物车,但以原始产品的价格! -
嗯,顺便说一句,我遇到了一个奇怪的行为,如果我在 order_wrapper 上调用 save(),则订单项根本不会进入购物车(但仍然没有错误)
标签: drupal drupal-7 drupal-commerce