12

I followed this tutorial to add a custom attribute to Customer. Then in Controller LoginPost.php, I want to get the value of that attribute of a particular customer to do some checking. But I found it completely different from Magento 1.X to retrieve the value of a custom attribute.

Anyone can suggest some methods? Thanks.

3
  • Maybe you misunderstood my question. The problem I'm facing is how to retrieve the value of a custom attribute, NOT creating a custom attribute. Thanks.
    – Ricky.C
    Commented Nov 22, 2015 at 13:45
  • Magento 1.X got $customerObj = Mage::getModel('customer/customer')->load($customer_id); $attr = $customerObj->getData('manager'); to retrieve the values. But in Magento2, I can't find the method to retrieve the values.
    – Ricky.C
    Commented Nov 22, 2015 at 13:46
  • 1
    Definitely not a duplicate. Did you read the questions guys ? Commented May 27, 2016 at 18:15

1 Answer 1

20

\Magento\Customer\Api\Data\CustomerInterface extends \Magento\Framework\Api\CustomAttributesDataInterface that have getCustomAttribute() method. You can use it to get custom attribute. ex. for test:

$customerRepository = $objectManager
        ->get('Magento\Customer\Api\CustomerRepositoryInterface');
$customer = $customerRepository->getById(1);
$cattrValue = $customer->getCustomAttribute('my_custom_attribute');
7
  • 1
    see \Magento\Framework\Api\AbstractExtensibleObject
    – KAndy
    Commented Nov 22, 2015 at 14:46
  • 2
    $customer->getCustomAttribute('custom_id '); returns a Magento\Framework\Api\AttributeValue Object ( [_data:protected] => Array ( [attribute_code] => custom_id [value] => a234 ) ) .Then how can I obtain the value 'a234' since I can't access to \Magento\Framework\Api\AttributeValue, so I have no ideas how to do that. Thanks
    – Ricky.C
    Commented Nov 23, 2015 at 2:21
  • 11
    Finally, I found it by my guess. $customer->getCustomAttribute('custom_id ')->getValue();
    – Ricky.C
    Commented Nov 23, 2015 at 3:04
  • 1
    Hi , Can you tell me how to save custom attribute..?
    – Elavarasan
    Commented Mar 15, 2016 at 16:32
  • 1
    To avoid Exception "Call to a member function getValue() on null" $value = $cattrValue ? $cattrValue->getValue() : null
    – PЯINCƎ
    Commented Feb 4, 2021 at 13:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.