Update Attribute Type in Magento 2 – How to Guide

attributesmagento2upgrade

I have to change the type of an attribute from text to decimal. I used upgrade script below. But it is not working

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

class UpgradeData implements UpgradeDataInterface
{

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


    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    { 
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        if (version_compare($context->getVersion(), '1.0.1', '<')) {

            $entityType = $eavSetup->getEntityTypeId('catalog_product');

            $eavSetup->updateAttribute($entityType, 'as_low_as', 'frontend_input','decimal', null);
        }
    }
}

How can we update the attribute type of an existing attribute?

Best Answer

$eavSetup->updateAttribute($entityType,'as_low_as','frontend_input','text');
$eavSetup->updateAttribute($entityType,'as_low_as','backend_type','decimal');
  • Frontend input should be text

  • Backend type should be decimal

If wanting it to be a price, don't forget to add backend model: Magento\Catalog\Model\Product\Attribute\Backend\Price. And frontend_input should be price, backend_type should be decimal.

$eavSetup->updateAttribute($entityType, 'as_low_as', 'frontend_input','price', null);
$eavSetup->updateAttribute($entityType,'as_low_as','backend_type','decimal');
$eavSetup->updateAttribute($entityType,'as_low_as','backend_model','Magento\Catalog\Model\Product\Attribute\Backend\Price');

[EDIT]

We can remove the old one, and add new one:

 if (version_compare($context->getVersion(), '1.0.4', '<')) {
        $eavSetup->removeAttribute($entityType, 'as_low_as');
        $eavSetup->addAttribute(
            'catalog_product',
            'as_low_as',
            [
                'label' => 'As Low As',
                'input' => 'price',
                'type' => 'decimal',
                'source' => '',
                'required' => false,
                'visible' => true,
                'system' => false,
                'default' => '',
                'backend' => 'Magento\Catalog\Model\Product\Attribute\Backend\Price',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'user_defined' => false,
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
Related Topic