Magento:将商品添加到购物车时如何更改商品价格 [英] Magento : how to change item price when adding it into the cart

查看:39
本文介绍了Magento:将商品添加到购物车时如何更改商品价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将商品添加到购物车中时,我希望能够以编程方式(而不是通过目录或购物车规则)更改商品价格.

I would like to be able to change an item price programmatically (not through catalog or cart rules) when I add it into the cart.

以下答案通过价格变化以编程方式将产品添加到购物车中显示更新购物车时的操作方法,而不是添加产品时的操作.

The following answer Programmatically add product to cart with price change shows how to do it when updating the cart but not when adding a product.

谢谢

推荐答案

您可以使用观察者类来收听checkout_cart_product_add_after,并使用产品的超级模式"为报价项设置自定义价格.

You can use an observer class to listen to checkout_cart_product_add_after, and use a product’s "Super Mode" to set custom prices against the quote item.

在您的/app/code/local/{namespace}/{yourmodule}/etc/config.xml中:

In your /app/code/local/{namespace}/{yourmodule}/etc/config.xml:

<config>
    ...
    <frontend>
        ...
        <events>
            <checkout_cart_product_add_after>
                <observers>
                    <unique_event_name>
                        <class>{{modulename}}/observer</class>
                        <method>modifyPrice</method>
                    </unique_event_name>
                </observers>
            </checkout_cart_product_add_after>
        </events>
        ...
    </frontend>
    ...
</config>

然后在/app/code/local/{namespace}/{yourmodule}/Model/Observer.php中创建一个Observer类

And then create an Observer class at /app/code/local/{namespace}/{yourmodule}/Model/Observer.php

<?php
    class <namespace>_<modulename>_Model_Observer
    {
        public function modifyPrice(Varien_Event_Observer $obs)
        {
            // Get the quote item
            $item = $obs->getQuoteItem();
            // Ensure we have the parent item, if it has one
            $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
            // Load the custom price
            $price = $this->_getPriceByItem($item);
            // Set the custom price
            $item->setCustomPrice($price);
            $item->setOriginalCustomPrice($price);
            // Enable super mode on the product.
            $item->getProduct()->setIsSuperMode(true);
        }

        protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item)
        {
            $price;

            //use $item to determine your custom price.

            return $price;
        }

    }

这篇关于Magento:将商品添加到购物车时如何更改商品价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆