Magento 2 Customer Attributes – How to Get Custom Customer Attribute Value

customer-attributemagento2

I've create a customer attribute using following installer data, InstallData.php file

<?php

namespace Amitshree\Marketplace\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
{
    /*
     *  attribute to identify a customer is vendor or not
     */
    const IS_VENDOR = 'is_vendor';
  /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;


    /**
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $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();
    .......... //snip
    $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

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

        /** @var $attributeSet AttributeSet */
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        /**
         *  create customer attribute is_vendor
         */
        $customerSetup->addAttribute(Customer::ENTITY, self::IS_VENDOR,
            [
            'type' => 'int',
            'label' => 'Is Vendor?',
            'input' => 'select',
            "source"   => "Amitshree\Marketplace\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();
......... //snip
$setup->endSetup();

I see attribute is properly created in customer section. Now when I'm trying to get value of this attribute in a controller, it doesn't return anything

<?php

namespace Amitshree\Marketplace\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        $customer =$this->customerRepositoryInterface->getById(5);
        print_r($customer->getCustomAttribute('is_vendor')->getValue());
    }
}

Also print_r($customer->getCustomAttributes()); returns an empty array. What I'm missing here.

Best Answer

Your code is working perfectly fine for me. The issue must be with no value for that attribute with the particular customer_is. Have you tried and saved is_vendor value for customer_id 5 once. I mean just try and change the value of is_vendor attribute and save that customer. Now execute your code, i hope you should get the value. If you have not followed above process then you will get empty array because that attribute did not have any value set for those customer id in database.

This is not an issue I must say, magento always work like that only, if you will create a new customer then things will work fine because customer form has that attribute 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).

Below code will do the work:-

$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');
}
Related Topic