4

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

以下答案以编程方式将产品添加到具有价格变化的购物车显示了在更新购物车时如何做到这一点,而不是在添加产品时。

谢谢

4

1 回答 1

10

您可以使用观察者类来监听 checkout_cart_product_add_after,并使用产品的“超级模式”针对报价项目设置自定义价格。

在您的 /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 类

<?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;
        }

    }
于 2013-02-26T08:48:48.520 回答