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?

brentwpeterson
6,1348 gold badges45 silver badges81 bronze badges
asked Nov 22, 2014 at 20:31
1
  • go to admin->catalog->Manage Attributes, and click the attributes and then Manage label options tab, then add/remove options. Commented Nov 24, 2014 at 9:12

1 Answer 1

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
3
  • Perhaps an explanation of what this chunk of code does might be useful. Commented Jun 24, 2016 at 6:50
  • @RobbieAverill. Is it more clear now? Commented Jun 24, 2016 at 7:13
  • Nice one Marius :) Commented Jun 24, 2016 at 7:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.