Creating Custom Option on Product Save
Until I find the exact problem here is the solution. Instead catalog_product_save_before
use the event catalog_product_prepare_save
. The downside of this is that the prepare_save
event is dispatched only when saving a product from the admin interface or the API. So if you are saving from a custom code this won't get triggered unless you trigger it manually.
I have a hunch that the problem has something to do with the Mage_Catalog_Model_Product::_beforeSave()
method. In there there is some processing of the custom options.
But catalog_product_save_before
is dispatched after this processing occurs, so while the custom options are processed in Mage_Catalog_Model_Product::_beforeSave()
they are actually empty because the event didn't fire yet so they are not added.
If you move the line parent::_beforeSave();
in the method I mentioned at the top of the method, the options are added (still twice, but they are added). I will post more when/if I find the problem.
[EDIT]
Found it. I was somehow right in the lines above.
Like I said the problem is that catalog_product_save_before
is dispatched after the custom options are processed. but this is why it doesn't work.
The custom options are saved in Mage_Catalog_Model_Product::_afterSave()
by this code:
$this->getOptionInstance()->setProduct($this)
->saveOptions();
But $this->getOptionInstance()
is populated with options in _beforeSave
when the options array is empty in your case. Hence...nothing to save.
If you still want to use the catalog_product_save_before
here is the code that should work.
//check that we haven't made the option already
$options = $product->getOptions();
if ($options){
foreach ($options as $option) {
if ($option['title'] == 'Auto Date & Time' && $option['type'] == 'date_time' && !$option['is_delete']) {
//we've already added the option
return;
}
}
}
$option = array(
'title' => 'Auto Date & Time',
'type' => 'date_time',
'is_require' => 1,
'sort_order' => 0,
'is_delete' => '',
'previous_type' => '',
'previous_group' => '',
'price' => '0.00',
'price_type' => 'fixed',
'sku' => ''
);
//don't use it like this because it has no effect
//$product->setProductOptions($options);
$product->setCanSaveCustomOptions(true);
//use it this way. Populate `$product->getOptionInstance()` directly
$product->getOptionInstance()->addOption($option);
//don't forget to state that the product has custom options
$product->setHasOptions(true);