Skip to content

Magento 2 : Update EAV Attribute

for example, we want to change ‘label’ and ‘sort order’¬†attribute ‘postcode’ from ‘customer_address’ attribute type, here upgrade data script

<?php


namespace MyCompany\MyModule\Setup;


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

class UpgradeData implements UpgradeDataInterface
{
	
	
	 private $customerSetupFactory;
	 private $eavSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
		EavSetupFactory $eavSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
		$this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();
        
		
		$entityAttributes = [
                 'customer_address' => [
                  'postcode' => [
			'frontend_label'=>'Zipcode',
			'sort_order'=>1,		
                       ]                
                  ],
                 ];
		
		
		$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
		
		$this->upgradeAttributes($entityAttributes, $customerSetup);
		
	
        $setup->endSetup();
    }
	
	
    protected function upgradeAttributes(array $entityAttributes, $customerSetup)
    {
        foreach ($entityAttributes as $entityType => $attributes) {
            foreach ($attributes as $attributeCode => $attributeData) {
                $attribute = $customerSetup->getEavConfig()->getAttribute($entityType, $attributeCode);
                foreach ($attributeData as $key => $value) {
                    $attribute->setData($key, $value);
                }
                $attribute->save();
            }
        }
    }
}

 

Comments are closed.