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
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communitytry 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>