Magento 1.8 – How to Fix Issues When Creating Custom Product Options Programmatically

csvcustom-optionsmagento-1.8product

I'm working on a product upload custom module. For that I want to create custom options programatically. I put following code in model. But it always add the custom option to the last product only. I want to add this custom option to all the products which are passing to this function.

(NOTE: The below function will invoke inside the csv file reading loop.)

public function saveSimpleProduct($sProduct) {

// Set product custom options.
                $customOptions = array(
                        'title' => 'Mixed Pack',
                        'type' => Mage_Catalog_Model_Product_Option::OPTION_TYPE_FIELD,
                        'is_require' => 0,
                        'sort_order' => 0
                );
       //       Mage::getSingleton('catalog/product_option')->unsetOptions();
                $sProduct->setProductOptions($customOptions)->setCanSaveCustomOptions(true)->save();
}

Any suggestions will be appreciated.
Thanks in advance.

Best Answer

Found the answer.

The Mage_Catalog_Model_Product_Option is a singleton object. Every time I'm passing the product it created the custom option and when the next product is passed it assigned the same option to that product. So the first product remains without the custom option. While I was debugging able to figured this out. And here I was trying to create a custom option for each product and assign it which didn't work out.

So the solution was create the custom option at once and assign it to all the products rather than creating one option per product.

public function saveSimpleProduct($collection)  {
 // $collection  is the product collection which i'm passing to the function.
 $customOption = array(
                'title'      => 'My Test Custom OPtion',
                'type'       => Mage_Catalog_Model_Product_Option::OPTION_TYPE_FIELD,
                'is_require' => 0,
                'sort_order' => 0
            );

            foreach ($collection as $key => $value)

                $product = Mage::getModel('catalog/product')->load($key);
                $optionInstance = $product->getOptionInstance()->unsetOptions();

                $product->setHasOptions(1);
                if (isset($option['is_require']) && ($option['is_require'] == 1)) {
                    $product->setRequiredOptions(1);
                }
                $optionInstance->addOption($customOption);
                $optionInstance->setProduct($product);
                $product->save();
             }
           }

Hope this will help someone.

Related Topic