0

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?

1
  • go to admin->catalog->Manage Attributes, and click the attributes and then Manage label options tab, then add/remove options. Nov 24 '14 at 9:12
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.

3
  • Perhaps an explanation of what this chunk of code does might be useful.
    – scrowler
    Jun 24 '16 at 6:50
  • @RobbieAverill. Is it more clear now?
    – Marius
    Jun 24 '16 at 7:13
  • Nice one Marius :)
    – scrowler
    Jun 24 '16 at 7:20

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.