I want to add and delete custom options to dropdown product attributes via custom code.
I have created a attribute name say myattrib, what I want to delete all it options and add my custom option how can I do it?
I want to add and delete custom options to dropdown product attributes via custom code.
I have created a attribute name say myattrib, what I want to delete all it options and add my custom option how can I do it?
//retrieve the attribute with the options
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'myattr');
//retrieve the options
$options = $attribute->getSource()->getAllOptions(false);
$toSave = array();
$toSave['delete'] = array();
//mark the options to delete
foreach ($options as $index => $option) {
$toSave['delete'][$option->getId()] = 1;//mark the option for delete
}
//add your new option
//negative array keys means that the options are new.
$toSave[-1][0] = 'Label here'; //-1 is just an index, 0 is the admin store view id
$order = array();
//set the position for the new option
$order[-1] = 1;
$result = array('value' => $toSave,'order' => $order);
//save the attribute with the new option
$attribute->setData('option', array($result);
$attribute->save();
The code is taken and adapted from the core code. It is similar to what happens in the admin controller when removing options and adding a new one.