Site icon MageComp Blog

How to assign guest customers orders into registered account in Magento 2

How to assign guest customers orders into registered account in Magento 2

In this article, I will help you to learn How to assign guest customer’s orders into a registered account in Magento 2. Also don’t forget to check our previously published How to Add Discount Component to Checkout Order Summary in Magento 2

Basically when any customer places an order from your store being a guest customer and later on that customer registers themself in your store then the orders they place being the guest customers don’t reflect on their account. Therefore to add these orders to the registered account you will require to add the below-given codes into the custom extension.

Steps to assign guest customers orders into registered account in Magento 2:

Step 1: Create Events.xml in the following path

app\code\Vendor\Extension\etc\events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="customer_save_after_data_object">

        <observer name="customer_save" instance="Vendor\Extension\Observer\Customersave" />

    </event>

</config>

Step 2: Now add Customersave.php in the following path

app\code\Vendor\Extension\Observer\Customersave.php

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');                  

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                foreach ($collection as $order){

                     $order->setCustomerId($savedCustomer->getId());

                     $order->setCustomerGroupId($savedCustomer->getGroupId());

                     $order->setCustomerIsGuest(1);

                     $order->save();

                }

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

}

Note: The above codes may take the load when the customer registers all the registered customer’s order details loads to set the customer id to each order.

Therefore, we will use the below method to reduce the load. Here we have used raw query so in a single query we will set it to multiple orders.

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $resourceConnection;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Magento\Framework\App\ResourceConnection $resourceConnection,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->resourceConnection = $resourceConnection;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                $gustOrderId = "";

                foreach ($collection as $item) {

                    $gustOrderId .= $item->getId() . ",";

                }

                $gustOrderId = rtrim($gustOrderId, ',');

                $tableName = $this->getTableName('sales_order');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_is_guest = 0,customer_group_id =" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

                $tableName = $this->getTableName('sales_order_grid');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_group=" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

    public function getTablename($tableName)

    {

        $connection = $this->resourceConnection->getConnection();

        $tableName = $connection->getTableName($tableName);

        return $tableName;

    }

}

That’s It.

Wrap Up:

Expectantly, all are able to implement the above illustration without any difficulties. To automate this functionality without following the complicated codes integrate the Magento 2 Assign Order to Customer extension.

In case of any errors you come through in between the implementation then let me know in the comment section below I will solve them out there. 

Share the illustration with your Magento Developer Friends.

Happy Reading.

Exit mobile version