Update: I followed the hints below, but the extension Attribute won't be saved. Do you have any suggestions to solve it?
I created an extension_attributes.xml file:
<config>
<extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
<attribute code="user_name" type="string">
<join reference_table="customer_extension" reference_field="customer_id" join_on_field="entity_id">
<field>user_name</field>
</join>
</attribute>
</extension_attributes>
</config>
And an Observer which is registered on the "customer_register_success" event:
<?php
namespace My\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class AfterCustomerSaveObserver implements ObserverInterface {
protected $_logger;
protected $_customerExtensionFactory;
protected $_customerRepository;
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->addDebug('AfterCustomerSaveObserver_Constructor_Begin');
$this->_customerRepository = $customerRepository;
$this->_customerExtensionFactory = $customerExtensionFactory;
$this->_logger->addDebug('AfterCustomerSaveObserver_Constructor_End');
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$this->_logger->addDebug('AfterCustomerSaveObserver_Execute_Begin');
/* try { */
$event = $observer->getEvent();
$customer = $event->getCustomer();
$customerExtension = $customer->getExtensionAttributes();
if ($customerExtension === null) {
$customerExtension = $this->_customerExtensionFactory->create();
}
$customerExtension->setUserName("Test123");
$customer->setExtensionAttributes($customerExtension);
$this->_customerRepository->save($customer);
//$customer->save();
/* } catch (\Exception $e) {
$this->_logger->critical($e);
} */
$this->_logger->addDebug('AfterCustomerSaveObserver_Execute_Begin');
}
}