I am trying to get certain user data by ID, and read that it's better not to use the object manager. So let's say I want to get a defined attribute, with this:

$user = $this->customerRepository->getById($user_id);
$attribute = $user->getCustomAttribute($attr);
if (!empty($attribute))
    return $attribute->getValue();

It doesn't work for anything I put in the $attr ($attribute is null), even things like email which are obviously defined. I'm probably completely misunderstanding how this works, but what is the "attribute code" if not the attribute name itself?

If this is not the correct way to retrieve arbitrary user data, please point me in the right direction.

EDIT: The class being injected for customerRepository is \Magento\Customer\Api\CustomerRepositoryInterface.

  • Which class you inject to customerRepository?
    – PY Yick
    Jun 8 '18 at 4:08
  • \Magento\Customer\Api\CustomerRepositoryInterface
    – Ynhockey
    Jun 10 '18 at 9:00

The CustomerRepositoryInterface::getById returns \Magento\Customer\Api\Data\CustomerInterface.

By default this interface is implemented by the Magento\Customer\Model\Data\Customer class.

You can study the both (the interface and the class that implements it) to see what available methods are there for retrieving customer attribute values.

This is not your typical Magento Data Object. the method getData($attribute_code = '') does not exist. So retrieving attribute values in this way does not work. OOP is enforced (thank God).

E.g. For email you can do $customer->getEmail();

This leaves us with retrieving the value of customAttributes. This are user(developer) defined attributes with the value is_custom = 1 Email is not a custom attribute so you can not retrieve it with $customer->getCustomAttribute('email').

When in doubt study the class definitions. That is why there are there.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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