I am trying to add a custom field(customer_type) value using observer to customer_address_entity table.The edit is done in BeforeAddressSaveObserver.php file.
The problem is the field is not getting saved and it just throws 'We can't save the address'. I have used this stack as an example
<?php
namespace MY-SITE\MY-MODULE\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class BeforeAddressSaveObserver implements ObserverInterface
{
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $_request;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
/**
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magento\Framework\App\ResourceConnection $resource
) {
$this->_request = $request;
$this->_resource = $resource;
}
private function getCustomerType() {
return $this->_request->getParams()['customer_type'];
}
private function getEntityId($observer) {
$customerAddress = $observer->getCustomerAddress();
$entityId = $customerAddress->getCustomer()->getEntityId();
return $entityId;
}
/* private function getConnection() {
return $this_resource->getConnection();
}*/
public function execute(EventObserver $observer)
{
if(!count($this->_request->getParams())) return $this;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('customer_address_entity');
$sql = "UPDATE " . $tableName . " SET customer_type = '" . $this->getCustomerType() . "' WHERE entity_id = " . $this->getEntityId($observer);
$connection->query($sql);
}
}