I followed this post to create my custom entity.
Now I registered an observer on the "customer_register_success" event and tried to save additional data in my custom entity. That doesn't work and I get the following error message:
Fatal error: Call to undefined method
Magento\Customer\Api\Data\CustomerExtension::save()
What is wrong?
Here is my code of the observer:
public function __construct(
\Psr\Log\LoggerInterface $logger, //log injection
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Customer\Api\Data\CustomerExtensionFactory $customerExtensionFactory
) {
$this->_logger = $logger;
$this->_logger->debug('AfterCustomerSaveObserver_Constructor_Begin');
$this->_customerRepository = $customerRepository;
$this->_customerExtensionFactory = $customerExtensionFactory;
$this->_logger->debug('AfterCustomerSaveObserver_Constructor_End');
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$this->_logger->debug('AfterCustomerSaveObserver_Execute_Begin');
try {
//Get Customer object
$event = $observer->getEvent();
$customer = $event->getCustomer();
//Get Controller
$controller = $event->getAccountController();
//Get Additional Data from Controller
$userName = $controller->getRequest()->getParam("user_name", "");
//Create Customer Extension object
$model = $this->_customerExtensionFactory->create(['customer_id' => $customer->getId()]);
//Set User Name
$model->setUserName($userName);
//Save Customer Extension object
$model->save();
}
catch(\Exception $e)
{
$this->_logger->critical($e);
$this->_logger->debug('exception');
}
$this->_logger->debug('AfterCustomerSaveObserver_Execute_End');
}
Best Answer
The
CustomerExtension
is not a model and thus doesn't have any ability to save itself, it is basically just a data container for extension attributes on for theCustomerInterface
. You would need to utilize theCustomerRepository
in order to save the data.In working with extension attributes you may have defined in a
extension_attributes.xml
more on DevDocs, here are some of the pieces involved: