Magento2 Add/Create and Get custom customer attribute value

To create a custom attribute for customer in magento, firstly we need to add a file in setup folder of our module and then add the given code. Below we are adding ‘is_vendor’ attribute which has two option yes/no.

 setup\InstallData.php 
namespace W3solver\Helloworld\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface {
    
    const IS_VENDOR = 'is_vendor';
    private $eavSetupFactory;
    protected $customerSetupFactory;
    private $attributeSetFactory;

    public function __construct(
    EavSetupFactory $eavSetupFactory, CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        $setup->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(Customer::ENTITY, self::IS_VENDOR, [
            'type' => 'int',
            'label' => 'Is Vendor?',
            'input' => 'select',
            "source" => "W3solver\Helloworld\Model\Config\Source\CustomerYesNoOptions",
            'required' => false,
            'default' => '0',
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 210,
            'position' => 210,
            'system' => false,
        ]);

        $is_vendor = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, self::IS_VENDOR)
                ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout'],
        ]);

        $is_vendor->save();
        $setup->endSetup();
    }
}

Above code will add a new attribute to customer, it can be checked on customer edit page in admin panel. So lets see how to get the value of this attribute. Firstly you need to inject customer repository interface in constructor

\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface

Now wherever you want to get the attribute value add the below code there:-

$customer = $this->customerRepositoryInterface->getById($customerId);
print_r($customer->getCustomAttribute('is_vendor')->getValue());


NOTE:-
Your code will only work for newly created customers because customer form has that attribute now and it will save its default value but already created customer did not have that attribute known to them, thus you need to write a small script to save all customer that were created previously and set whatever value you want for them. (this will be just one time process).

To set the value for the attribute to previous customer add the below code (try not to use object manager and inject those class through constructor:-

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerObj = $objectManager->create ('Magento\Customer\Model\Customer') ->getCollection ();
        foreach ($customerObj as $customerObjdata) {
            
            $customermodel = $objectManager->create ('Magento\Customer\Model\Customer');
            $customerData = $customermodel->getDataModel();
            $customerData->setId($customerObjdata->getData('entity_id'));
            $customerData->setCustomAttribute('is_vendor', 0);
            $customermodel->updateData($customerData);
            
            $customerResource = $objectManager->create ('\Magento\Customer\Model\ResourceModel\CustomerFactory')->create();
            $customerResource->saveAttribute($customermodel, 'is_vendor');
        }

Drop in your comments if you face any issue.

Leave a Comment.