Magento2 Custom Entity – Save Data Failed

custommagento2model

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 the CustomerInterface. You would need to utilize the CustomerRepository 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:

// Get the entity Interface from the entity Repository
$entity = $this->entityRepositoryInterface->get($entityId);

// Get existing ExtensionAttributes or create one
$entityExtension = $entity->getExtensionAttributes();
if ($entityExtension == null) {
    $entityExtension = $this->entityExtensionFactory->create();
}

// Set a value on your attribute
$entityExtension->setMyAttribute($value);

// Set the ExtensionAttributes back to the entity
$entity->setExtensionAttributes($entityExtension);

// Save the entity using the repository
$this->entityRepository->save($entity);
Related Topic