Remove Product Attribute When Uninstalling a Module

0

Hello Friends,

Sometimes we create attributes during the module installation but while removing the module the attributes and table remain in the Magento database.

In this blog, we will see How to remove the catalog product attribute with the Uninstaller script. When you RUN the uninstall module command it will remove those attributes.

Updating products and details are regular. In this case, cron jobs are necessary to use to manage all eCommerce business. Learn to set up cron jobs in Magento 2 development.

Quick Tip:How to Setup Magento 2 Cron Jobs?

Please check below steps:

Step 1: Create Uninstall.php in the following location

app/code/[Namespace]/[Module]/Setup/Uninstall.php
<?php
namespace [Namespace]\[Module]\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class Uninstall implements \Magento\Framework\Setup\UninstallInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }
    
    public function uninstall(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
    {
        $setup->startSetup();

        $eavSetup = $this->eavSetupFactory->create();

        $eavSetup->removeAttribute(1,'attribute_code');
        
        $setup->endSetup();
    }
}

As you can see in the above code, you just need to replace your attribute code with the ‘attribute_code’ word.

Step 2: To test, RUN the below command

Open your terminal and RUN below code:
php bin/magento module:uninstall -r [Namespace]_[Module]

Thanks for reading this post!

About the author

I’m Magento Certified Developer having quite 5 years of commercial development expertise in Magento as well as in Shopify. I’ve worked primarily with the Magento and Shopify e-commerce platform, managing the complexities concerned in building e-commerce solutions tailored to a client’s specific desires.

Related Posts

Leave a Reply