Magento 2 getExtensionAttributes return null
-
29-03-2021 - |
Question
I am writing an Observer to Magento\Customer\Account\Index
but the Objects from class \Magento\Customer\Model\Customer
return null when getExtensionAttributes is executed.
$customer = $customerFactory->create()->load($customerID);
//$customerRepository->get($customerID);
$ext = $customer->getExtensionAttributes();
if($ext == null){
throw new \Exception(" var ext = null");
}
I used CustomerRepository and CustomerFactory to get $customer
No correct solution
OTHER TIPS
You don't need to use CustomerFactory for getting customer data.
CustomerRepository is enough for getting a customer data.
You need to changes the code if($ext == null){
to if($ext === null){
.
//$customer = $customerFactory->create()->load($customerID);
$customerRepository->get($customerID);
$ext = $customer->getExtensionAttributes();
if($ext === null){
throw new \Exception(" var ext = null");
}
===
means Identical match condition which is vastly used at PHP 7,
It is happening because the Magento\Customer\Model\Customer
is not an Extensible Model (does not extend the \Magento\Framework\Api\AbstractExtensibleObject
class), it extending the \Magento\Framework\Model\AbstractModel
which is not an extensible object. You must use the repository, because it will return the instance of Magento\Customer\Model\Data\Customer
which is extensible object.
Or you can use your code, but with Magento\Customer\Model\Data\CustomerFactory
.