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?
brentwpeterson
6,1348 gold badges45 silver badges81 bronze badges
asked Nov 22, 2014 at 20:31
user1799722
9803 gold badges31 silver badges82 bronze badges
-
go to admin->catalog->Manage Attributes, and click the attributes and then Manage label options tab, then add/remove options.Manikandan Arunachalam– Manikandan Arunachalam2014年11月24日 09:12:00 +00:00Commented Nov 24, 2014 at 9:12
1 Answer 1
//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.
answered Mar 26, 2015 at 8:29
Marius
199k55 gold badges431 silver badges837 bronze badges
Explore related questions
See similar questions with these tags.
default