2012-10-30 72 views
0

我有這樣的觀察者Magento的購物車數量不可

<events> 
<sales_quote_add_item> 
     <observers> 
      <reservation_observer_order_save_before1> 
       <type>singleton</type> 
       <class>Mageec_Total_Model_Observer</class> 
       <method>updatePrice</method> 
      </reservation_observer_order_save_before1> 
     </observers> 
</sales_quote_add_item> 
</events> 

和功能updatePrice下面去:

public function updatePrice($observer){ 

    $event = $observer->getEvent(); 

    $quote_item = $event->getQuoteItem(); 


    if ($quote_item->getProductType() == "virtual"){ 
     $new_price = (float)$quote_item->getProduct()->getPrice(); 
     $quote_item->setOriginalCustomPrice($new_price); 

     $qty = Mage::getSingleton('checkout/cart')->getSummaryQty(); //return 0 
        $qty = $quote_item->getQty(); //return 0 too 
     Mage::log(print_r($qty,true)); 



     $quote_item->setTotalPrice($new_price * $qty); 
    } 
} 

我不能讓車數量或至少quoteitem數量。我認爲這是因爲這個觀察者在購物車對象被填充之前執行。那麼在這種情況下,我可以在哪裏獲得數量?

回答

0

,我發現自己的解決方案。 當我們把第一個產品放到購物車時,運行sales_quote_add_item觀察者。但它是第一個產品,購物車還沒有保存。之前的代碼,我得到購物車quanty返回0.之前的解決方案是在訂單處理之前保存購物車。代碼示例低於:

public function modifyPrice(Varien_Event_Observer $observer){ 
     $cart = Mage::getSingleton('checkout/cart'); 
     $cart->save(); 


     $quote_item = $observer->getQuoteItem(); 
    if ($quote_item->getProductType() == "virtual"){ 
      $new_price = (float)$quote_item->getProduct()->getPrice(); 
     $quote_item->setOriginalCustomPrice($new_price); 

     $totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //Total items in cart 
     Mage::log("Total Product in Cart : "); 
     Mage::log(print_r($totalItemsInCart, true)); 

     $qty = 1; 

     if($totalItemsInCart) 
     {    
      Mage::log("Total Product in Cart : ".$totalItemsInCart);   
      $cart = Mage::getModel('checkout/cart')->getQuote()->getData(); 
      Mage::log("Total Quantity In Cart : ".(int)$cart['items_qty']); 
      $qty = (int)$cart['items_qty']; 
     } 






     $quote_item->setTotalPrice($new_price * $qty); 
     $quote_item->save(); 
    } 

    return $this; 
} 

正如你可以看到線:

$cart = Mage::getSingleton('checkout/cart'); 
$cart->save(); 

這些的人是解決方案。

0

你可以試試這個代碼,如果不工作讓我通知

$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //Total items in cart 

if($totalItemsInCart) 
{    
    echo "Total Product in Cart : ".$totalItemsInCart;   
    $cart = Mage::getModel('checkout/cart')->getQuote()->getData(); 
    echo "Total Quantity In Cart : ".(int)$cart['items_qty'];  
} 
+0

if block never run,$ totalItemsInCart is empty –

+0

@Portnyagin Mikhail您是否在產品添加了購物車?嘗試print_r($ totalItemsInCart)並查看集合。 – Muk

+0

是的,我已經添加了。 print_r($ totalItemsInCart)返回0.我可以在購物車中看到產品 –