Add a new attribute in eav_attribute

Here I need to add a new attribute ‘dealer_name’. So in an existing dealer module added a new folder controller and created a file installData.php

<?php
namespace JJ\Dealer\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
    private $eavSetupFactory;

    private $eavConfig;

    private $attributeResource;

    public function __construct(
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeResource = $attributeResource;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->removeAttribute(Customer::ENTITY, "dealer_name");
        $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
        $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

        $eavSetup->addAttribute(Customer::ENTITY, 'dealer_name', [
            // Attribute parameters
            'type' => 'varchar',
            'label' => 'Dealer name',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 990,
            'position' => 990,
            'system' => 0,
        ]);
        $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'dealer_name');
        $attribute->setData('attribute_set_id', $attributeSetId);
        $attribute->setData('attribute_group_id', $attributeGroupId);
        $attribute->setData('used_in_forms', [
            'adminhtml_customer',
            'customer_account_create',
        ]);
        $this->attributeResource->save($attribute);
    }
}

we need to delete this(dealer) module in php myadmin and do the following

  • php bin/magento setup:upgrade
  • php bin/magento setup:di:compile
  • php bin/magento setup:static-content:deploy -f
  • sudo chmod 777 -R /var/www/html/Corp-design/

Then we see the attribute in the eav_attribute database.

Leave a comment

Your email address will not be published. Required fields are marked *