1

Can we delete product attribute options by using label?

For example say attribute:color has options like green, red, yellow how to delete red from this? I used below code.

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $eavConfig = $objectManager->get('Magento\Eav\Model\Config'); $attribute = $eavConfig->getAttribute('catalog_product', 'color); $id = $attribute->getAttributeId(); $options = $attribute->getSource()->getAllOptions(); foreach ($options as $option) { $options['delete'][$option['value']] = true; $options['value'][$option['value']] = true; } $eavSetup = $this->_objectManager->get('Magento\Eav\Setup\EavSetup'); $eavSetup->addAttributeOption($options); 

It is deleting all the options. I need to delete specific option.

1
  • It works great. But what if i want to add a new option? Can i use something like $options['create'][$option['value']] = true; $options['value'][$option['Yellow']] = true; Commented Feb 4, 2019 at 10:35

2 Answers 2

5

Try the below code:

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $eavAttribute = $objectManager->create('Magento\Eav\Model\Config'); $attribute = $eavAttribute->getAttribute('catalog_product', 'color'); $options = $attribute->getSource()->getAllOptions(); foreach ($options as $option) { if($option['label'] == 'Red'){ $options['delete'][$option['value']] = true; $options['value'][$option['value']] = true; } } $setupObject = $objectManager->create('Magento\Eav\Setup\EavSetup'); $setupObject->addAttributeOption($options); ?> 
3
  • I have used your code with slight changes, deleting options in bulk by reading the json into array with foreach, i have posted the answer below, that is not working. can you pls check it where i am wrong Commented Jan 23, 2019 at 4:45
  • Create a question, I ll check and answer. Also provide the json value in correct format. Commented Jan 23, 2019 at 8:16
  • here is my question, magento.stackexchange.com/questions/258787/… Commented Jan 23, 2019 at 8:19
0
 "OptionValues": [ { "OptionId": "22", "OptionName": "Test" }, { "OptionId": "21", "OptionName" : "Test 2" } <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $eavAttribute = $objectManager->create('Magento\Eav\Model\Config'); $attribute = $eavAttribute->getAttribute('catalog_product', 'color'); $options = $attribute->getSource()->getAllOptions(); foreach($OptionValues as $optValue){ $optionIdVal = $optValue['OptionName']; foreach ($options as $option) { if($option['label'] == $optionIdVal){ $options['delete'][$option['value']] = true; $options['value'][$option['value']] = true; } } } $setupObject = $objectManager->create('Magento\Eav\Setup\EavSetup'); $setupObject->addAttributeOption($options); ?> 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.