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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值