Magento – How to add a Product option value programmatically in magento

magento-1magento-1.7

I have a product with a custom option named as Instructions which is a textarea type and is not required.

Now suppose some one doesn't fill it. how to add this value through by program.

What i have done so far is , I have managed to update the option value through a action :

$options = $item->getOptions();

foreach ($options as $option) 
    { 

    switch (true) 
        {

            case (strtolower($option->getCode()) == 'info_buyrequest') :
                $unserialized = unserialize($option->getValue());
                $unserialized['options'][2] = $info_option_value;
                $option->setValue(serialize($unserialized));
                break;

                case ($option->getCode() == "option_2") :
                $option->setValue($info_option_value);
                break;
        }

    }
    $item->setOptions($options)->save(); 
    Mage::getSingleton('checkout/cart')->save();

But I am not getting how to create a similar action which adds the option value.

Hope anyone can help

Best Answer

Your question is a bit confusing.

What you are saying/asking is how to add the field to 'info_buy_request' options, if it was not filled in by a user.

If the user did not fill it in, what exactly do you want to add? The field with NULL as the value? If the field does not exist in the options, then that explicitly means it was not populated, which should be enough, should it not? Why the need to populate it? (and again, with what?)

also, your way of iterating over the item options is not needed. You can get to the data as follows:

$infoBuyRequest = $item->getOptionByCode('info_buyRequest'); 
if (is_object($infoBuyRequest)) { 
    $buyRequest = new Varien_Object(unserialize($infoBuyRequest->getValue())); 
} 

Now your data is in an object - $buyRequest and can be accessed/manipulated as an object