Magento2 | PWA | GraphQL

Assign Guest Orders to Customer Accounts in Magento 2


Assign guest orders to existing customer accounts in Magento 2. Easily link guest orders to the correct customer account with a controlled admin workflow.

This module allows Magento 2 administrators to assign a guest order to an existing customer account directly from the order view. It provides a controlled way for the Customer Care team to search for the correct customer and associate the guest order with their account, making the order available within the customer’s order history.

The feature is particularly useful when a customer places an order as a guest but later needs the order linked to their registered account.

You can find the complete module on GitHub at Magelearn_AsignOrder

Or Check the images below for a better understanding of the functionality of this module.

Let's start it by creating a custom extension. 

Create a folder inside app/code/Magelearn/AsignOrder

Add registration.php file in it:

<?php

use \Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_AsignOrder', __DIR__);

Add composer.json file in it:

{
    "name": "magelearn/module-assign-guest-order",
    "description": "Magento2 Module to Assign the guest orders to Customers.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\AsignOrder\\": ""
        }
    }
}

Add etc/module.xml file in it:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_AsignOrder">
        <sequence>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

Now to display the "Assign Customer" button on Sales order view page,

First we will create Layout, Block and associate template files.

Add view/adminhtml/layout/sales_order_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magelearn_AsignOrder::css/email-popup.css" media="all" />
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magelearn\AsignOrder\Block\Adminhtml\Customer\AssignGuestOrder"  name="magelearn_customer_assign"
                   template="Magelearn_AsignOrder::customer/assignguestorder.phtml"/>
        </referenceContainer>
    </body>
</page>

Now add view/adminhtml/templates/customer/assignguestorder.phtml file.

<?php

declare(strict_types=1);

/** @var Magelearn\AsignOrder\Block\Adminhtml\Customer\AssignGuestOrder $block
* @var $escaper Magento\Framework\Escaper */ ?> <?php if ($block->isGuestOrder()) : ?> <div id="magelearn_assign_customer" class="modal ui-front" style="display:none;"> <form class="form assign-order-customer" novalidate action="<?= $escaper->escapeUrl($block->getAdminPostUrl()) ?>" method="post" data-mage-init='{"validation": {"errorClass": "mage-error"}}' > <div class="wrapper"> <p><?= $escaper->escapeHtml(__('Search and assign this guest order to a customer account.')) ?></p> <?= /* @noEscape */ $block->getBlockHtml('formkey') ?> <input type="hidden" name="order_id" value="<?= (int) $block->getOrderId() ?>" /> <input type="hidden" id="customer-id" name="customer_id" /> <div id="customer-grid-container"> <div class="admin__data-grid-loading-mask"> <?= $escaper->escapeHtml(__('Loading customers...')) ?> </div> </div> <div class="message-container"></div> <div class="actions"> <button class="action assign-customer primary" title="<?= $escaper->escapeHtmlAttr(__('Assign Customer')) ?>" type="button"> <span><?= $escaper->escapeHtml(__('Assign Customer')) ?></span> </button> </div> </div> </form> </div> <script type="text/x-magento-init"> { "*": { "magelearnAssignCustomer": { "postUrl": "<?= $escaper->escapeUrl($block->getAdminPostUrl()) ?>", "gridUrl": "<?= $escaper->escapeUrl($block->getGridUrl()) ?>", "buttonLabel": "<?= $escaper->escapeJs((string) __('Assign Customer')) ?>" } } } </script> <?php endif; ?>

And as per the JS (script) defined in phtml file, we will add view/adminhtml/requirejs-config.js
var config = {
    map: {
        '*': {
            magelearnAssignCustomer: 'Magelearn_AsignOrder/js/assign-customer'
        }
    }
};
And add JS file at view/adminhtml/web/js/assign-customer.js
define([
    'Magento_Ui/js/modal/modal',
    'jquery',
    'mage/translate'
], function ($modal, $, $t) {
    'use strict';

    var assignModal;
    var $emailHref = $('table.order-account-information-table tr a[href^="mailto:"]');

    function showError(message) {
        $('.message-container').html(
            '<div class="message message-error">' +
            '<div>' + message + '</div>' +
            '</div>'
        );
    }

    function showSuccess(message) {
        $('.message-container').html(
            '<div class="message message-success">' +
            '<div>' + message + '</div>' +
            '</div>'
        );
    }

    function clearMessages() {
        $('.message-container').html('');
    }

    function showGridError(message) {
        $('#customer-grid-container').html(
            '<div class="message message-error">' +
            '<div>' + message + '</div>' +
            '</div>'
        );
    }

    var magelearnAssignCustomerPopup = function (config) {
        if (!assignModal) {
            assignModal = $('#magelearn_assign_customer').modal({
                title: $t('Assign Customer'),
                modalClass: 'assign-customer-modal',
                innerScroll: true,
                responsive: true,
                buttons: [{
                    text: $t('Close'),
                    class: 'action-default action-dismiss',
                    click: function () {
                        this.closeModal();
                    }
                }],
                closed: function () {
                    $('#customer-id').val('');
                    $('#customer-grid-container').html(
                        '<div class="admin__data-grid-loading-mask">' +
                        $t('Loading customers...') +
                        '</div>'
                    );
                    clearMessages();
                }
            });
        }

        assignModal.modal('openModal');

        $.ajax({
            url: config.gridUrl,
            type: 'GET',
            showLoader: true,
            success: function (html) {
                $('#customer-grid-container').html(html);
            },
            error: function () {
                showGridError(
                    $t('Unable to load customers.')
                );
            }
        });   
    };

    var assignCustomerFormPost = function (config) {
        var customerId = $('#customer-id').val();
        var $form = $('#magelearn_assign_customer').find('form.assign-order-customer');
        var $assignButton = $('button.assign-customer');
        if (!customerId) {
            showError(
                $t('Please select a customer.')
            );

            return false;
        }

        $assignButton.prop('disabled', true).addClass('disabled');

        var url = $form.attr('action');
        var postData = $form.serialize();

        clearMessages();

        $.ajax({
            url: url,
            dataType: 'json',
            type: 'POST',
            showLoader: true,
            data: postData,
            success: function (response) {
                if (response.error === false) {
                    showSuccess(
                        response.message
                    );
                    setTimeout(function () {
                        assignModal.modal(
                            'closeModal'
                        );
                        if (response.redirectUrl) {
                            window.location.href =
                                response.redirectUrl;
                        }
                    }, 2000);
                } else {
                    showError(
                        response.message
                    );
                }
            },
            error: function () {
                showError(
                    $t(
                        'An error occurred while assigning the order.'
                    )
                );
            },
            complete: function () {
                $assignButton.prop('disabled', false).removeClass('disabled');
            }
        });

        return false;
    };

    return function (config) {
        $(document).on(
            'change',
            'input[name="selected_customer"]',
            function () {
                $('#customer-id').val($(this).val());
                clearMessages();
            }
        );

        if ($emailHref.length > 0) {
            var html = '<button id="magelearnAssignCustomerPopup">' +
                       config.buttonLabel + '</button>';
            if (!$('#magelearnAssignCustomerPopup').length) {
                $emailHref.parent().append(html);
            }

            $(document).on('click', '#magelearnAssignCustomerPopup', function () {
                magelearnAssignCustomerPopup(config);
            });
        }

        $(document).on('click', 'button.assign-customer', function () {
            assignCustomerFormPost(config);
        });

        $(document).on('submit', 'form.assign-order-customer', function (e) {
            e.preventDefault();
        });
    };
});
Now Add Block file at app/code/Magelearn/AsignOrder/Block/Adminhtml/Customer/AssignGuestOrder.php

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Block\Adminhtml\Customer;

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

class AssignGuestOrder extends Template
{
    private const ADMIN_URL_POPUP = 'assigncustomer/customer/assignguestorder';
    private const ADMIN_URL_GRID = 'assigncustomer/customer/grid';

    /**
     * @param array<string, mixed> $data
     */
    public function __construct(
        Context $context,
        private readonly OrderRepositoryInterface $orderRepository,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $data
        );
    }

    public function getAdminPostUrl(): string
    {
        return $this->getUrl(self::ADMIN_URL_POPUP);
    }

    public function getOrderId(): int
    {
        return (int) $this->getRequest()->getParam('order_id');
    }

    public function getOrder(): OrderInterface
    {
        $orderId = $this->getOrderId();
        if (!$orderId) {
            throw new NoSuchEntityException(
                __('Order not found.')
            );
        }

        return $this->orderRepository->get($orderId);
    }

    public function isGuestOrder(): bool
    {
        return (bool) $this->getOrder()->getCustomerIsGuest();
    }

    public function getGridUrl(): string
    {
        return $this->getUrl(self::ADMIN_URL_GRID);
    }
}

Now to make a Admin URL as per the path defined in Block,
We will add etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="assigncustomer" frontName="assigncustomer">
            <module name="Magelearn_AsignOrder" before="Magento_Backend" />
        </route>
    </router>
</config>

And Define Controller at Controller/Adminhtml/Customer/AssignGuestOrder.php
<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Controller\Adminhtml\Customer;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Auth\Session;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\Config\Share;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
use Magelearn\AsignOrder\Api\OrderMigrationServiceInterface;

class AssignGuestOrder extends Action
{
    public const ADMIN_RESOURCE = 'Magento_Customer::manage';

    public function __construct(
        Context $context,
        private readonly Session $authSession,
        private readonly Share $shareConfig,
        private readonly JsonFactory $resultJsonFactory,
        private readonly OrderRepositoryInterface $orderRepository,
        private readonly CustomerRepositoryInterface $customerRepository,
        private readonly LoggerInterface $logger,
        private readonly OrderMigrationServiceInterface $orderMigrationService
    ) {
        parent::__construct($context);
    }

    public function execute(): Json
    {
        $resultJson = $this->resultJsonFactory->create();

        try {
            $orderId = (int) $this->getRequest()->getParam('order_id');
            $customerId = (int) $this->getRequest()->getParam('customer_id');

            if (!$orderId || !$customerId) {
                throw new LocalizedException(
                    __('Missing order or customer information.')
                );
            }

            $order = $this->orderRepository->get($orderId);
            $customer = $this->customerRepository->getById($customerId);

            $orderWebsiteId = (int) $order->getStore()->getWebsiteId();
            $customerWebsiteId = (int) $customer->getWebsiteId();

            if (!$order->getCustomerIsGuest()) {
                throw new LocalizedException(
                    __('This order is already assigned to a customer.')
                );
            }

            if (!$this->shareConfig->isGlobalScope() && $orderWebsiteId !== $customerWebsiteId) {
                throw new LocalizedException(
                    __('Customer belongs to a different website.')
                );
            }

            $adminUser = $this->authSession->getUser();

            $adminUsername = (string) $adminUser?->getUserName();

            $this->orderMigrationService->migrateOrderToCustomer(
                $order,
                $customer
            );

            $comment = __(
                'Order assigned to customer account by admin "%1". Customer ID: %2, Email: %3.',
                $adminUsername,
                $customer->getId(),
                $customer->getEmail(),
            );

            $order->addCommentToStatusHistory($comment);

            $this->orderRepository->save($order);

            $this->logger->info(
                'Guest order migrated',
                [
                    'order_id' => $order->getId(),
                    'order_increment_id' => $order->getIncrementId(),
                    'customer_id' => $customer->getId(),
                    'customer_email' => $customer->getEmail(),
                    'admin_user' => $adminUsername,
                ]
            );

            $resultJson->setData([
                'error' => false,
                'message' => __(
                    'Order #%1 assigned to customer %2.',
                    $order->getIncrementId(),
                    $customer->getEmail()
                ),
                'redirectUrl' => $this->_url->getUrl(
                    'sales/order/view',
                    ['order_id' => $order->getId()]
                ),
            ]);
        } catch (LocalizedException $e) {
            $resultJson->setData([
                'error' => true,
                'message' => $e->getMessage(),
            ]);
        } catch (\Exception $e) {
            $this->logger->error(
                'Failed to assign customer to guest order',
                [
                    'order_id' => $orderId ?? null,
                    'customer_id' => $customerId ?? null,
                    'exception' => $e->getMessage(),
                ]
            );

            $resultJson->setData([
                'error' => true,
                'message' => __('Something went wrong while assigning the order.'),
            ]);
        }

        return $resultJson;
    }
}

As Per the highlighted in code, we will add Api/OrderMigrationServiceInterface.php

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Api;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\OrderInterface;

interface OrderMigrationServiceInterface
{
    /**
     * Migrate a guest order to a customer account
     *
     * @param OrderInterface $order Guest order to migrate
     * @param CustomerInterface $customer Target customer account
     * @return void
     * @throws LocalizedException
     */
    public function migrateOrderToCustomer(
        OrderInterface $order,
        CustomerInterface $customer
    ): void;
}

Also for grid URL, we will add Controller/Adminhtml/Customer/Grid.php file.

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Controller\Adminhtml\Customer;

use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Raw;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\View\LayoutFactory;

class Grid extends Action
{
    public const ADMIN_RESOURCE = 'Magento_Customer::manage';

    public function __construct(
        Action\Context $context,
        private readonly LayoutFactory $layoutFactory,
        private readonly RawFactory $resultRawFactory
    ) {
        parent::__construct($context);
    }

    public function execute(): Raw
    {
        $layout = $this->layoutFactory->create();
        $grid = $layout
            ->createBlock(
                \Magelearn\AsignOrder\Block\Adminhtml\Customer\Grid::class
            )
            ->toHtml();

        return $this->resultRawFactory
            ->create()
            ->setContents($grid);
    }
}

And the associate block at Block/Adminhtml/Customer/Grid.php

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Block\Adminhtml\Customer;

use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Helper\Data;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Magento\Store\Model\System\Store;
use Magelearn\AsignOrder\Block\Adminhtml\Customer\Renderer\Checkbox;

class Grid extends Extended
{
    private const ADMIN_URL_GRID = 'assigncustomer/customer/grid';

    /**
     * @param array<string, mixed> $data
     */
    public function __construct(
        Context $context,
        Data $backendHelper,
        private readonly CollectionFactory $collectionFactory,
        private readonly Store $systemStore,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $backendHelper,
            $data
        );
    }

    protected function _construct(): void
    {
        parent::_construct();

        $this->setId('customer_assign_grid');
        $this->setDefaultSort('entity_id');
        $this->setUseAjax(true);
    }

    protected function _prepareCollection(): self
    {
        $collection = $this->collectionFactory->create();

        $collection->addAttributeToSelect([
            'firstname',
            'lastname',
            'email',
        ]);

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    protected function _prepareColumns(): self
    {
        $this->addColumn(
            'select_customer',
            [
                'header' => __('Select'),
                'renderer' =>
                    Checkbox::class,
                'filter' => false,
                'sortable' => false,
            ]
        );

        $this->addColumn(
            'entity_id',
            [
                'header' => __('ID'),
                'index' => 'entity_id',
            ]
        );

        $this->addColumn(
            'firstname',
            [
                'header' => __('First Name'),
                'index' => 'firstname',
            ]
        );

        $this->addColumn(
            'lastname',
            [
                'header' => __('Last Name'),
                'index' => 'lastname',
            ]
        );

        $this->addColumn(
            'email',
            [
                'header' => __('Email'),
                'index' => 'email',
            ]
        );

        $this->addColumn(
            'website_id',
            [
                'header' => __('Website'),
                'index' => 'website_id',
                'type' => 'options',
                'options' => $this->systemStore->getWebsiteOptionHash(),
            ]
        );

        return parent::_prepareColumns();
    }

    public function getGridUrl(): string
    {
        return $this->getUrl(
            self::ADMIN_URL_GRID,
            ['_current' => true]
        );
    }
}

And as per highlighted in the Block file, we will add Block/Adminhtml/Customer/Renderer/Checkbox.php

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Block\Adminhtml\Customer\Renderer;

use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer;
use Magento\Framework\DataObject;

class Checkbox extends AbstractRenderer
{
    public function render(DataObject $row): string
    {
        return sprintf(
            '<input type="radio"
                name="selected_customer"
                value="%d" />',
            (int) $row->getId()
        );
    }
}

Now to implement the Service Contract pattern in the Dependency Injection (DI), We will add
etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="magelearn_order_check" xsi:type="object">\Magelearn\AsignOrder\Console\OrderCheck</item>
                <item name="magelearn_order_assign_customer" xsi:type="object">\Magelearn\AsignOrder\Console\AssignOrderToCustomer</item>
            </argument>
        </arguments>
    </type>

    <type name="Magelearn\AsignOrder\Console\OrderCheck">
        <arguments>
            <argument name="orderRepository" xsi:type="object">Magento\Sales\Api\OrderRepositoryInterface\Proxy</argument>
        </arguments>
    </type>
    <!-- Order Repository -->
    <preference for="Magelearn\AsignOrder\Api\OrderRepositoryInterface"
                type="Magelearn\AsignOrder\Model\OrderRepository"/>
    <!-- Order Migration Service -->
    <preference for="Magelearn\AsignOrder\Api\OrderMigrationServiceInterface"
                type="Magelearn\AsignOrder\Service\OrderMigrationService"/>
</config>

Now as per the Highlighted code above, we will add:
Service/OrderMigrationService.php file.

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Service;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\OrderInterface;
use Psr\Log\LoggerInterface;
use Magelearn\AsignOrder\Api\OrderMigrationServiceInterface;
use Magelearn\AsignOrder\Api\OrderRepositoryInterface;

class OrderMigrationService implements OrderMigrationServiceInterface
{
    public function __construct(
        private readonly OrderRepositoryInterface $orderRepository,
        private readonly LoggerInterface $logger
    ) {
    }

    /**
     * Migrate a guest order to a customer account.
     *
     * This method:
     * 1. Validates that the order is a guest order.
     * 2. Updates the in-memory order customer data.
     * 3. Defers persistence to the caller.
     *
     * @throws LocalizedException
     */
    public function migrateOrderToCustomer(
        OrderInterface $order,
        CustomerInterface $customer
    ): void {
        // Validate: order must be a guest order
        if (!$order->getCustomerIsGuest()) {
            throw new LocalizedException(
                __('Order #%1 is already assigned to a customer.', $order->getIncrementId())
            );
        }

        try {
            // Update order with new customer_id
            $this->orderRepository->reassignOrderToCustomer(
                $order,
                $customer
            );
        } catch (\Exception $e) {
            $this->logger->error(
                'Failed to migrate guest order',
                [
                    'order_id' => $order->getId(),
                    'customer_id' => $customer->getId(),
                    'error' => $e->getMessage(),
                ]
            );

            throw new LocalizedException(
                __('Failed to migrate order #%1: %2', $order->getIncrementId(), $e->getMessage()),
                $e
            );
        }
    }
}

And Api/OrderRepositoryInterface.php file.

<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Api;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\OrderInterface;

interface OrderRepositoryInterface
{
    /**
     * Reassign order to a customer
     *
     * @param OrderInterface $order
     * @param CustomerInterface $customer
     * @return void
     * @throws LocalizedException
     */
    public function reassignOrderToCustomer(OrderInterface $order, CustomerInterface $customer): void;

    /**
     * Get order by increment ID
     *
     * @param string $incrementId
     * @return OrderInterface
     * @throws LocalizedException
     */
    public function getByIncrementId(
        string $incrementId
    ): OrderInterface;
}
Will also add Model/OrderRepository.php file.
<?php

declare(strict_types=1);

namespace Magelearn\AsignOrder\Model;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magelearn\AsignOrder\Api\OrderRepositoryInterface;

class OrderRepository implements OrderRepositoryInterface
{
    public function __construct(
        private readonly CollectionFactory $orderCollectionFactory
    ) {
    }

    /**
     * Updates the order with the specified customer's information.
     *
     * The caller is responsible for persisting the order.
     */
    public function reassignOrderToCustomer(
        OrderInterface $order,
        CustomerInterface $customer
    ): void {
        try {
            $order->setCustomerId((int) $customer->getId());
            $order->setCustomerIsGuest(false);
            $order->setCustomerGroupId((int) $customer->getGroupId());
            $order->setCustomerFirstname((string) $customer->getFirstname());
            $order->setCustomerLastname((string) $customer->getLastname());
            $order->setCustomerEmail((string) $customer->getEmail());
        } catch (\Exception $e) {
            throw new LocalizedException(
                __(
                    'Failed to reassign order %1: %2',
                    $order->getIncrementId(),
                    $e->getMessage()
                )
            );
        }
    }

    /**
     * Get order by increment ID
     *
     * @throws LocalizedException
     */
    public function getByIncrementId(
        string $incrementId
    ): OrderInterface {
        $order = $this->orderCollectionFactory->create()
            ->addFieldToFilter('increment_id', $incrementId)
            ->getFirstItem();

        if (!$order->getId()) {
            throw new LocalizedException(
                __('Order "%1" does not exist.', $incrementId)
            );
        }

        return $order;
    }
}
0 Comments On "Assign Guest Orders to Customer Accounts in Magento 2"

Back To Top