skip to Main Content

My custom module observes the sales_order_place_after event, and creates a customer and associates the customer with the order by setting customerId for the order.

What works?

  • Order is placed
  • Customer is created
  • The customerId is updated in the order database

What doesn’t work?

  • The customerId is instantly set back to NULL by another script

How can I find out what script updates the customerId to NULL again, after my observer is done running?

2

Answers


  1. You should change event to sales_model_service_quote_submit_success

    Example Code (Magento 2 Version): events.xml

    <event name="sales_model_service_quote_submit_success">
            <observer name="quote_submit_success_observer" instance="NamespaceModuleNameObserverGenerateObserver" />
        </event>
    

    GenerateObserver.php

     ...
     public function execute(MagentoFrameworkEventObserver $observer)
     {
        /** @var MagentoSalesModelOrder $order */
            $order = $observer->getEvent()->getData('order');
    
        // Ensure customer is registered
        $this->registerCustomer($order);
        $order->getResource()->save($order);
     }
    
    protected function registerCustomer(
        MagentoSalesApiDataOrderInterface $order
    ) {
        /** @var MagentoSalesModelOrder $order */
    
        if ($order->getCustomerId() === null) {
            // Load customer by email, create if not exists.
            try {
                $customerData = $this->customerRepository->get($order->getCustomerEmail());
            } catch (MagentoFrameworkExceptionNoSuchEntityException $e) {
                $customerData = $this->orderCustomerManager->create($order->getId());
            }
    
            $order->setCustomerId($customerData->getId());
        }
    
        return $this;
    }
     ...
    
    Login or Signup to reply.
  2. I had the same problem – my assumption was that calling the save method on the order triggered whatever was listening to the sales_order_save_before/after events, one of which was setting the customer ID back to null. I worked around this by saving only the attributes I wanted, rather than triggering a save on the entire order:

    $order
        ->setCustomerId($customer->getId())
        ->setCustomerIsGuest(0)
        ->setCustomerGroupId($customer->getGroupId());
    
    $order->getResource()
        ->saveAttribute($order, 'customer_id'      )
        ->saveAttribute($order, 'customer_is_guest')
        ->saveAttribute($order, 'customer_group_id');
    

    This allowed me to successfully associate a customer with the order in Magento EE 1.14.3.10 using the sales_model_service_quote_submit_success event.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search