我已经成功地在Magento中建立了一个观察者,它结合了自定义的添加到购物车事件.现在,在某种情况下,我需要停止添加到购物车事件(或者甚至将其删除?),并向用户发送消息.
目前,此产品设置为允许每个订单的最大数量为1.如果用户尝试添加超过1,Magento将显示错误消息并阻止将该项添加到购物车.
屏幕截图:[link] http://cl.ly/image/3V2C2j1S0f37
理想情况下,我想模仿观察者的相同功能,但我完全不知道如何解决这个问题,因为我是Magento的新手.
我读过我需要抛出异常.但是当我这样做时,它只是把我带到了一个错误页面.想知道我是否需要以某种方式添加此修改版本:
Mage::helper('cataloginventory')->__('The maximum quantity allowed for purchase is %s.', '<span class="sku-failed-qty" id="sku-stock-failed-' . $item->getId() . '">' . ($item->getQtyMaxAllowed() * 1) . '</span>');
Run Code Online (Sandbox Code Playgroud)
任何帮助或指针将不胜感激.
您可以尝试以下方法.这将检查数量是否大于1.如果是这种情况,那么我们将数量更新为1.我们还添加通知消息,以便用户了解数量变化.
<checkout_cart_product_add_after>
<observers>
<company_module_name>
<type>singleton</type>
<class>Company_Module_Model_Observer</class>
<method>checkItem</method>
</company_module_name>
</observers>
Run Code Online (Sandbox Code Playgroud)
public function checkItem($obj) {
//check if qty is more then 1
if($obj->getProduct()->getQty() > 1) {
//set notice to inform the visitor that there is a maximum
Mage::getSingleton('core/session')->addNotice('The maximum quantity allowed for purchase is 1.');
//get the event
$event = $obj->getEvent();
//get the product we have added
$product = $event->getProduct();
//get the quote item
$quoteItem = $event->getQuoteItem();
//change the qty to 1 allowed
$quoteItem->setQty(1);
//recalc totals
$quoteItem->getQuote()->collectTotals();
//save the item
$quoteItem->getQuote()->save();
}
Run Code Online (Sandbox Code Playgroud)
=====编辑======
另一种选择是:
<controller_action_predispatch_checkout_cart_add>
<observers>
<aquait_aquait_name>
<type>singleton</type>
<class>Aquait_Aquait_Model_Observer</class>
<method>checkfunction</method>
</aquait_aquait_name>
</observers>
</controller_action_predispatch_checkout_cart_add>
public function checkfunction($observer)
{
if ($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') {
$productId = Mage::app()->getRequest()->getParam('product');
$product = Mage::getModel('catalog/product')->load($productId);
if (Mage::app()->getRequest()->getParam('qty') > 1) {
Mage::getSingleton('core/session')->addNotice('The maximum quantity allowed for purchase is 1.');
Mage::app()->getResponse()->setRedirect($product->getProductUrl());
}
}
}
Run Code Online (Sandbox Code Playgroud)