[转]Magento 产品添加购物车时修改价格
我们其实参照的是后台创建订单的代码
位于:
app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
主要代码:
if (empty($info['action']) || !empty($info['configured'])) { $item->setQty($itemQty); $item->setCustomPrice($itemPrice); $item->setOriginalCustomPrice($itemPrice); $item->setNoDiscount($noDiscount); $item->getProduct()->setIsSuperMode(true); $item->getProduct()->unsSkipCheckRequiredOption(); $item->checkData(); } else { $this->moveQuoteItem($item->getId(), $info['action'], $itemQty); }
那么 当我们想要修改产品价格的时候其实可以写在相应的事件中
例如 事件 checkout_cart_product_add_after 也可以写在sales_quote_add_item 等事件中
例如写在 checkout_cart_product_add_after事件中
首先在 config.xml 添加代码:
<events> <checkout_cart_product_add_after> <observers> <produts_price_update> <class>Simael_Update_Model_Observer</class> <method>productsPriceUpdate</method> </produts_price_update> </observers> </checkout_cart_product_add_after> </events>
然后定义函数 productsPriceUpdate()
主要代码
$new_price = $updatePrice['price']; $quote_item->setCustomPrice($new_price); $quote_item->setOriginalCustomPrice($new_price); // Enable super mode on the product. $quote_item->getProduct()->setIsSuperMode(true); //$quote_item->save();
注意这里的save函数是被注释掉了 ,起初我是添加了这个函数的
但是未登录且未添加任何商品的情况下直接添加这个可以修改价格的产品
提示无法添加。
报错信息:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`sales_flat_quote_item`, CONSTRAINT `FK_SALES_FLAT_QUOTE_ITEM_QUOTE_ID_SALES_FLAT_QUOTE_ENTITY_ID` FOREIGN KEY (`quote_id`) REFERENCES `sales_flat_quote` (`entity_id`) ON DELETE C
我解读的意思是你添加数据到 sales_flat_quote_item 表中,但是这个表关联了外键到 sales_flat_quote 表的 entity_id字段。
此时save ,sales_flat_quote 表还没有这个 entity_id呢
网上给出的解答是:
You should not save quote item object in observer, so just remove this line $quote_item->save(); It will save the object automatically, as it is being passed by reference.
原文链接:https://blog.csdn.net/m0sh1/article/details/49341691