Magento : programmatically add custom options for products

I've found plenty of places on magento forums and websites that mention adding custom options to products : none of them seemed to work on my installation (1.5) so I suppose each version has its own tweaks. The technique below catches a specific event that is fired when the product is being saved from the admin. A good tutorial on Magento events can be found here, pseudo official list of events can also be found on Magento's wiki, probably outdated though. What I need now is to find the appropriate code to delete options from a product. not simple either... Anyone tried?

The way I did is the following

  • create a custom module PoleOuest_CustomOptions_Model_Observer 
    app/local/PoleOuest/CustomOptions/Model/Observer.php




     class PoleOuest_CustomOptions_Model_Observer
     {
    
          public function Add_CustomOptions_Automatically($observer) {
    
                $event = $observer->getEvent();
        $product = $event->getProduct();
    
       // if ($product->getDecodirect())
         //   {
            $optionData = array(
      'is_delete'         => 0,
        'is_require'        => false,
        'previous_group'    => '',
        'title'             => 'want to preorder ? ',
        'type'              => 'checkbox',
        'price_type'        => 'fixed',
        'price'             => '20.0000',
        'sort_order'        => 0,
    
               'values'            => array(
            array(
                'is_delete'     => 0,
                'title'         => 'preorder',
                'price_type'    => 'percent',
                'price'         => -20,
                'sku'           => 'product sku',
                'option_type_id'=> -1,
            ))
    
            );
            $product->setHasOptions(1);
    
           $opt = Mage::getModel('catalog/product_option');
            $opt->setProduct($product);
            $opt->addOption($optionData);
            $opt->saveOptions();      
    
                   Mage::log("option should be added now");
         // }
          }
    
     }
  • catch product save before event in app/local/PoleOuest/CustomOptions/etc/config.xml
    <?xml version="1.0" encoding="utf-8"?>
    <config>
        <modules>
            <PoleOuest_CustomOptions>
                <version>0.0.1</version>
            </PoleOuest_CustomOptions>
        </modules>
        <global>
            <events>
                <catalog_product_save_before>
                    <observers>
                        <custom_options>
                            <type>singleton</type>
                            <class>PoleOuest_CustomOptions_Model_Observer</class>
                            <method>Add_CustomOptions_Automatically</method>
                        </custom_options>
                    </observers>
                </catalog_product_save_before>
            </events>
        </global>
    </config>