0

I would like to show a popup that gives an overview of the product that the customer has just bought it, so I need to display a popup with item name and its other attributes like color, image, name etc when we add this product in cart. this popup I need to be display when clicking add to cart button on product page.

I use an observer checkout_cart_add_product_complete I try everything but I can't get the last add to cart product name of the associated product. I use ->getLastAddedProductId(true) seems to not working, I try to use this code but it seems to not working:

   $main_product = $observer->getEvent()->getProduct();
    $associated_product = $observer->getEvent()->getQuoteItem();
    $productSku = $main_product ->getSku();  //for configurable product
    $productQty = $main_product ->getQty();  //for configurable product
    if($product->getTypeID() == 'configurable'){
      //to get the id or sku of associated product use the following.
      $simple_product_id = $quoteitem->getProduct()->getId();
      $simple_product_sku = $quoteitem->getProduct()->getSku();
    }

I use the code below and this is working but only thing is this code get me the last product and I need to get the current:

  $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
    $max = 0;
    $lastItem = null;
    foreach ($items as $item){
        if ($item->getId() > $max) {
            $max = $item->getId();
            $lastItem = $item;
        }
    }
    if ($lastItem){
        $_product = $lastItem->getProduct();
        $xproductsku = $_product->getSku();
       $xproductname = $_product->getName();               
       $xproductqty = $_product->getQty();  
       $xproductprice = $_product->getPrice();   
       $xproducturl = $_product->getUrl();
    }

here is another post where you can view my entire code: https://stackoverflow.com/questions/28642855/how-can-i-add-ajax-notice-when-the-product-was-successfully-added-to-cart

you have an idea how can I make this to work?

My entire Observer.php file:

    public function addToCartEvent($observer)
    {
        $request = Mage::app()->getFrontController()->getRequest();
        if (!$request->getParam('in_cart') && !$request->getParam('is_checkout'))
        {
            Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
            $quote = Mage::getSingleton('checkout/cart')->getQuote();
            $grandTotal = $quote->getGrandTotal();
            $subTotal = $quote->getSubtotal();
            $session = Mage::getSingleton('checkout/session');
            $shippingTaxamount = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount');

            // get coupon discounted value            

            $totals = $quote->getTotals(); //Total object
            if (isset($totals['discount']) && $totals['discount']->getValue())
            {
                $discount = Mage::helper('core')->currency($totals['discount']->getValue()); //Discount value if applied
            }
            else
            {
                $discount = '';
            }

            //get discount value end     

            $xitems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
            $max = 0;
            $lastItem = null;
            foreach ($xitems as $xitem)
            {
                if ($xitem->getId() > $max)
                {
                    $max = $xitem->getId();
                    $lastItem = $xitem;
                    $attributeSetModel1 = Mage::getModel("eav/entity_attribute_set")->load($lastItem->getProduct()->getAttributeSetId());
                    $attributeSetName1 = $attributeSetModel1->getAttributeSetName();
                    $parentIds1 = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($lastItem->getProduct()->getId());
                    if ($lastItem->getProduct()->getTypeId() == 'simple' && empty($parentIds1) && $attributeSetName1 == 'Default')
                    {
                        $child = $lastItem;
                    }
                    else
                    {
                        $child = $lastItem->getOptionByCode('simple_product')->getProduct();
                    }
                }
            }





            $html = '';
            $productser = '';
            foreach ($session->getQuote()->getAllVisibleItems() as $item)
            {
                if ($lastItem)
                {
                    $xproduct = $lastItem->getProduct();
                    $xproductsku = $xproduct->getSku();
                    $xproductname = $xproduct->getName();
                    $xproductqty = $xproduct->getQty();
                    $xproductprice = $xproduct->getPrice();
                    $xproducturl = $xproduct->getUrl();
                }






                $productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
                if ($productOptions)
                {
                    if (isset($productOptions['options']))
                    {
                        foreach ($productOptions['options'] as $_option)
                        {
                            $productser = $_option['option_id'] . ',' . $_option['option_value'];
                        }
                    }
                    $superAttrString = '';
                    if (isset($productOptions['info_buyRequest']['super_attribute']))
                    {
                        foreach ($productOptions['info_buyRequest']['super_attribute'] as $key => $_superAttr)
                        {
                            $attr = Mage::getModel('catalog/resource_eav_attribute')->load($key);
                            $label = $attr->getSource()->getOptionText($_superAttr);
                            $superAttrString .= '<dt> ' . $attr->getAttributeCode() . ' </dt> <dd> ' . $label . ' </dd>';
                        }
                    }
                    if ($superAttrString):
                        $superAttrString . '&qty=1';
                    endif;
                }








                $productid = $item->getId();
                $html .='<li id="li-' . $productid . '">';
                $product_id = $item->getProduct()->getId();
                $productsku = $item->getSku();
                $productname = $item->getName();
                $productqty = $item->getQty();
                $_product = Mage::getModel('catalog/product')->load($product_id);
                $url = Mage::getUrl(
                                'checkout/cart/deleteqty', array(
                            'id' => $productid,
                            Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => Mage::helper('core/url')->getEncodedUrl()
                                )
                );










                $count = $quote->getItemsCount();
                $html .='<div class="item-thumbnail">';
                if ($item->hasProductUrl()):
                    $html .='<a href="' . $item->getUrl() . '" title="' . $item->getName() . '" class="product-image"><img src="' . Mage::helper('catalog/image')->init($item->getProduct(), 'thumbnail') . '" width="50" height="50" alt="' . $this->escapeHtml($item->getName()) . '" /></a>';
                else:
                    $html .='<span><img src="' . Mage::helper('catalog/image')->init($item->getProduct(), 'thumbnail') . '" width="50" height="50" alt="' . $item->getName() . '" /></span>';
                endif;
                $html .='</div>';
                $html .='<div class="mini-basket-content-wrapper">
                        <div class="mini-cart-name">
                        <a class="item-name" href="' . $item->getUrl() . '">' . $productname . '</a> <span class="item-price"><span class="price">$' . $item->getPrice() . '</span></span>
                <div class="truncated_full_value">
        <dl class="item-options">
            <dd class="truncated">
                <div class="truncated_full_value">
                    <dl class="item-options">
                        ' . $superAttrString . '
                    </dl>
                </div>
            </dd>
        </dl>
     </div>

        <div class="product-cart-sku">SKU: # ' . $productsku . '</div>
            <div class="product-qty">Quantity: ' . $productqty . '</div>
                    </div>  
                   </div>
                        <div class="clearfix"></div>';
                $html .='</li>';



$collection = Mage::getSingelton('checkout/session')->getQuote()->getItemsCollection(); 
$collection->getSelect()->order('created_at DESC'); 
$latestItems = $collection->getFirstItem();
$productse = $latestItems->getProduct();

$productnamese=$productse->getName();

                $xhtml .='<div class="product-qty">Quantity: ' . $productnamese . '</div>';


            }








            $_response = Mage::getModel('ajaxminicart/response')
                    ->setProductName($observer->getProduct()->getName())
                    ->setCarttotal($grandTotal)
                    ->setCartsubtotal($subTotal)
                    ->setCartcount($count)
                    ->setDiscount($discount)
                    ->setShippingtaxamount($shippingTaxamount)
                    ->setCartitem($html)
                     ->setMessage($xhtml);

            //append updated blocks

            $_response->addUpdatedBlocks($_response);
            $_response->send();
        }

        if ($request->getParam('is_checkout'))
        {
            Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
            $_response = Mage::getModel('ajaxminicart/response')
                    ->setProductName($observer->getProduct()->getName())
                    ->setMessage(Mage::helper('checkout')->__('%s was added into cart.', $observer->getProduct()->getName()));
            $_response->send();
        }
    }

    public function updateItemEvent($observer)
    {
        $request = Mage::app()->getFrontController()->getRequest();
        if (!$request->getParam('in_cart') && !$request->getParam('is_checkout'))
        {
            Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
            $quote = Mage::getSingleton('checkout/cart')->getQuote();
            $grandTotal = $quote->getGrandTotal();
            $subTotal = $quote->getSubtotal();
            $shippingTaxamount = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount');

            // get coupon discounted value            

            $totals = $quote->getTotals(); //Total object
            if (isset($totals['discount']) && $totals['discount']->getValue())
            {
                $discount = Mage::helper('core')->currency($totals['discount']->getValue()); //Discount value if applied
            }
            else
            {
                $discount = '';
            }

            //get discount value end                

            $_response = Mage::getModel('ajaxminicart/response')
                    ->setCarttotal($grandTotal)
                    ->setCartsubtotal($subTotal)
                    ->setShippingtaxamount($shippingTaxamount)
                    ->setDiscount($discount)
                    ->setMessage(Mage::helper('checkout')->__('Item was updated'));

            //append updated blocks
            $_response->addUpdatedBlocks($_response);
            $_response->send();
        }

        if ($request->getParam('is_checkout'))
        {
            Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
            $_response = Mage::getModel('ajaxminicart/response')
                    ->setMessage(Mage::helper('checkout')->__('Item was updated'));
            $_response->send();
        }
    }

    public function getConfigurableOptions($observer)
    {

        $is_ajax = Mage::app()->getFrontController()->getRequest()->getParam('ajax');
        if ($is_ajax)
        {
            $_response = Mage::getModel('ajaxminicart/response');
            $_response = Mage::getModel('ajaxminicart/response');
            $product = Mage::registry('current_product');
            if (!$product->isConfigurable() && !$product->getTypeId() == 'bundle')
            {
                return false;
                exit;
            }

            //append configurable options block

            $_response->addConfigurableOptionsBlock($_response);
            $_response->send();
        }

        return;
    }

    public function getGroupProductOptions()
    {

        $id = Mage::app()->getFrontController()->getRequest()->getParam('product');
        $options = Mage::app()->getFrontController()->getRequest()->getParam('super_group');
        if ($id)
        {

            $product = Mage::getModel('catalog/product')->load($id);
            if ($product->getData())
            {
                if ($product->getTypeId() == 'grouped' && !$options)
                {
                    $_response = Mage::getModel('ajaxminicart/response');
                    Mage::register('product', $product);
                    Mage::register('current_product', $product);
                    //add group product's items block
                    $_response->addGroupProductItemsBlock($_response);
                    $_response->send();
                }
            }
        }
    }

3 Answers 3

3

The call to

Mage::getSingleton('checkout/session')->getLastAddedProductId(true);

... is actually clearing the session variable after it is read. Magento uses magic methods extensively. In this case you are using the __call() magic method which in turn uses the getData() method. In Mage_Core_Model_Session_Abstract_Varien you will see that they override the default behaviour of getData() to expect the second parameter to be a boolean (The first parameter to getData() is the key name for the value you are looking for). That boolean is a flag telling the session to clear the variable after reading.

You could always listen for the checkout_cart_product_add_after event and add the item to your own variable in the session. That event is actually fired on the line before setLastAddedProductId() is called.

Refered links:

Edit 1:

You're almost there - try this code:

$collection = Mage::getSingelton('checkout/session')->getQuote()->getItemsCollection();

$collection->getSelect()->order('created_at DESC');

$latestItem = $collection->getFirstItem();

Note that when you get the latest quote item, you're not actually obtaining the product. To get the actual product, you would need to add this line:

$product = $latestItem->getProduct();

Edit 2:

Use this below code

Code to get the the full product information (where 3 is the configurable product Id)

$product = Mage::getModel('catalog/product')->load(3); 

$childProducts = Mage::getModel('catalog/product_type_configurable')
                ->getUsedProducts(null,$product);

foreach($childProducts as $child) {
    print_r($child->getName());  // You can use any of the magic get functions on this object to get the value
}

Edit 3:

You can also get by sku

$associated_products = $_product->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();

foreach ($associated_products as $assoc) 
{
    $assocProduct   = Mage::getModel('catalog/product')->load($assoc->getId());
}
37
  • Thank you Nanda yes I know that but I don;t know how to make this with my code, I edited my post can you see my code below in stackoverfloe link
    – Robert
    Feb 25, 2015 at 9:26
  • Can you try my new edit code ?
    – Nandakumar
    Feb 25, 2015 at 9:32
  • yes thank you but there is an error I don;t know why, I try to get the name like this $productnamese=$product->getName(); ohh and I forget, I need the associated simple product name in configurable
    – Robert
    Feb 25, 2015 at 9:35
  • Are you getting other than names ? Please post your code
    – Nandakumar
    Feb 25, 2015 at 9:36
  • Whether its working now ?
    – Nandakumar
    Feb 25, 2015 at 9:37
1

The easiest way is:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$itemsCollection = $quote->getAllVisibleItems();
if($itemsCollection) {
    $lastQuoteItem = array_pop($quoteItemsCollection);
    $lastAddedProduct = $lastQuoteItem->getProduct();
}
1
  • This might give you weird results with bundles and configurable products, because you don't filter out child items. Jan 28, 2016 at 19:43
0

Below Code is used for getting cart items

$cart = new Mage_Checkout_Model_Cart();

$cart->init();

foreach ($cart->getItems() as $item) {

   // we can wrap our request in this IF statement

   if (!$item->getParentItemId()) {

   }
}

It looks like their sort by adding, so just get the last looped item.

1
  • Thank you but I am able to get all products, I need to get the current one, all I want to do is to replace this ->setMessage(Mage::helper('checkout')->__('%s was added into cart.', $observer->getProduct()->getName())); with all product details: image, Name, description
    – Robert
    Feb 25, 2015 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.