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();

Any suggestions will be appreciated. Thanks in advance.

  • can you paste the code that is calling this function (it seems that you might be passing the same product into it) – pzirkind Mar 17 '14 at 18:10
  • @pzirkind: I checked, It's not passing the same product. – Sukeshini Mar 18 '14 at 4:02

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();

                if (isset($option['is_require']) && ($option['is_require'] == 1)) {

Hope this will help someone.

| improve this answer | |
  • very interesting – pzirkind Mar 18 '14 at 15:58
  • @DavidManners Thanks for reminding. I was forgotten – Sukeshini May 23 '14 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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