Skip to content

Instantly share code, notes, and snippets.

@bh-ref
Last active December 28, 2021 21:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bh-ref/2a788f206f8c3d833e43 to your computer and use it in GitHub Desktop.
Save bh-ref/2a788f206f8c3d833e43 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);
}
}
@TheRealJAG
Copy link

__construct doesn't require a description.

@AboElnoor
Copy link

This removes options only, I need to delete options' values too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment