Skip to content

Instantly share code, notes, and snippets.

@skmezanul
Forked from bh-ref/RemoveOptions.php
Created December 9, 2020 20:28
Show Gist options
  • Save skmezanul/77732878803d7771626bf77921ac0d08 to your computer and use it in GitHub Desktop.
Save skmezanul/77732878803d7771626bf77921ac0d08 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;
/**
* Init
*
* @param EavSetupFactory $eavSetupFactory
* @param AttributeFactory $attributeFactory
*/
public function __construct(
EavSetupFactory $eavSetupFactory,
AttributeFactory $attributeFactory
)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->attributeFactory = $attributeFactory;
}
/**
* delete options from an attribute
*
* @param ModuleDataSetupInterface $setup
*/
public function deleteOptions(ModuleDataSetupInterface $setup)
{
/** @var \Magento\Eav\Setup\EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$entityTypeId = $eavSetup->getEntityTypeId(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_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