0

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);
    }
}
  • Saving a field in address before address save, do you have an option to try to save after customer_address_save_after. Because do you think the row is inserted in database at the time you are updating the db table? – dev_67Commerce Nov 22 '17 at 13:10
  • may be $entityId not correct here get parentID customer_address_entity plz check database – matinict Sep 5 '18 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.