Skip to content

Instantly share code, notes, and snippets.

@dupadhyay3
Forked from bh-ref/RemoveOptions.php
Last active June 6, 2019 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dupadhyay3/3a09f04e4f91224c87aa073d4eaf33df to your computer and use it in GitHub Desktop.
Save dupadhyay3/3a09f04e4f91224c87aa073d4eaf33df to your computer and use it in GitHub Desktop.
Remove/Delete Product Attribute Options in Magento 2
<?php
namespace Vendor\ModuleName\Options;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
class RemoveOptions
{
/**
* EAV setup factory
*
* @var EavSetupFactory
*/
protected $eavSetupFactory;
/**
* EAV product attribute factory
*
* @var AttributeFactory
*/
protected $attributeFactory;
/**
* EAV Setup Interface
*
* @var ModuleDataSetupInterface
*/
protected $setupInterface;
/**
* Init
*
* @param EavSetupFactory $eavSetupFactory
* @param AttributeFactory $attributeFactory
* @param ModuleDataSetupInterface $setupInterface
*/
public function __construct(
EavSetupFactory $eavSetupFactory,
AttributeFactory $attributeFactory,
ModuleDataSetupInterface $setupInterface
)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->attributeFactory = $attributeFactory;
$this->setupInterface = $setupInterface;
}
/**
* delete options from an attribute
*
* @param ModuleDataSetupInterface $setup
*/
public function deleteOptions()
{
$setup = $this->setupInterface;
/** @var \Magento\Eav\Setup\EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$entityTypeId = $eavSetup->getEntityTypeId(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE);
// your attribute code
$attributeCode = 'my_already_existing_attribute';
// IMPORTANT:
// use $this->attributeFactory->create() before loading the attribute,
// or else the options you want to delete will be cached and you cannot
// delete other options from a second attribute in the same request
$attribute = $this->attributeFactory->create()->loadByCode($entityTypeId, $attributeCode);
$options = $attribute->getOptions();
$optionsToRemove = [];
foreach($options as $option)
{
if ($option['value'])
{
$optionsToRemove['delete'][$option['value']] = true;
$optionsToRemove['value'][$option['value']] = true;
}
}
$eavSetup->addAttributeOption($optionsToRemove);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment