您可以尝试以下方法。这将检查数量是否大于 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>
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();
}
===== 编辑 ======
另一种选择是:
<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());
}
}
}