Magento2: get custom customer attribute value
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');
}
You can get all customer custom attribute using below way,
Just replace your code with below one and remove var/generation
folder and clear system cache and check.
<?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->resultPageFactory = $resultPageFactory;
$this->customerRepositoryInterface = $customerRepositoryInterface;
parent::__construct($context);
}
public function execute()
{
$customerId = 5;
$customer = $this->customerRepositoryInterface->getById($customerId);
$customerAttributeData = $customer->__toArray();
$isVendor = $customerAttributeData['custom_attributes']['is_vendor']['value'];
echo "<pre>";print_r($customerAttributeData['custom_attributes']);exit;
}
}