0

In Magento 2.x,

If I have created a custom attribute and then need to remove that attribute and also need to remove that attribute value that is assigned to that entity.

How can I do programmatically (Using setup script)?

Thank you

1 Answer 1

0

try below code. If your module has already been installed then use UgradeData to remove the attribute.

if you removed a custom attribute using a script the value is automatically removed.

app/code/Vendor/Module/Setup/UpgradeData.php :

namespace Vendor\Module\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;


class UpgradeData implements UpgradeDataInterface
{

    private $eavSetupFactory;
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '2.0.1') < 0) {
            $this->removeCustomerAttribute($setup);
            $this->removeProductAttribute($setup);
        }

        $setup->endSetup();
    }


    private function removeCustomerAttribute(ModuleDataSetupInterface $setup)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->removeAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'customer_attribute'
        );
    }

     private function removeProductAttribute(ModuleDataSetupInterface $setup)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->removeAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'product_attribute'
        );
    }
}

change your module version (make sure to increase it) in

app/code/Vendor/Module/etc/module.xml :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="2.0.1"></module>
</config>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.