Pergunta

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.

Foi útil?

Solução

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.

Docs:

https://devdocs.magento.com/guides/v2.0/extension-dev-guide/attributes.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top