Magento 1 – Add Custom Option and Price to Product in Cart Using Observer

cartcustom-optionsevent-observermagento-1product

I want to add custom option to quoteitem using observer which observer checkoutCartProductAddAfter event and fires after product added to cart.

public function checkoutCartProductAddAfter(Varien_Event_Observer $observer)
{

 $item = $observer->getQuoteItem();  
  $item->addOption(new Varien_Object(
            array(
                    'product' => $item->getProduct(),
                    'label' => 'Free Gifts',
                    'value' => 'Spend $50 and get gift product worth $9.99'
                 )
        ));
    return;

}

My observer is working
but i am not able to add custom option to added product. please provide help to add custom option using observer to just added product.

Best Answer

@Tim gave a talk about this issue on the weekend: https://docs.google.com/presentation/d/1efPznQSVTrT1HAD1xQvCPC-Tgvr8jYok4X7ZEJhm9jE/edit

What you want is Method 2: Add Following Event in Config.xml

<sales_quote_collect_totals_before>
<observers>
<hackathon_presentation>
<type>singleton</type>
<class>modulename/observer</class>
<method>salesQuoteAddressCollectTotalsBefore</method>
</hackathon_presentation>
</observers>
</sales_quote_collect_totals_before>

In Observer.php add following Method

   public function salesQuoteAddressCollectTotalsBefore($observer)
    {
        $quote = $observer->getQuote();
        $quote_items = $quote->getItemsCollection();
        foreach ($quote_items as $item) {
            $additionalOptions = array(
                array(
                    'code'  => 'my_code',
                    'label' => 'This text is displayed through additional options',
                    'value' => 'ID is ' . $item->getProductId() . ' and SKU is ' . $item->getSku()
                )
            );
            $item->addOption(
                array(
                     'code'  => 'additional_options',
                     'value' => serialize($additionalOptions),
                )
            );
        }
    }

Here is more about this topic:

https://stackoverflow.com/questions/9334115/magento-change-custom-option-value-before-adding-it-to-cart/9344336#9344336

and more:

https://stackoverflow.com/questions/9412074/magento-quote-order-product-item-attribute-based-on-user-input/9496266#9496266