2

What is most optimized way to create customer programmatically from order ?

As i need to create customer for a guest user, what will be the better way of implementing it ?

Hamendra Sunthwal
  • 2,488
  • 10
  • 39

2 Answers2

0

Please try the below reference code(Convert guest customer to regular customer on successful order place in magento 2). You can run that code by creating a custom script in the Magento root

 $collection     = $this->filter->getCollection($this->collectionFactory->create());
    $collectionSize = $collection->getSize();
    $count          = 0;
    /** @var $order \Magento\Sales\Model\Order */

    foreach ($collection as $order) {
        $websiteId  = $order->getStore()->getWebsiteId();
        $storeId    = $order->getStore()->getId();

        $customerData = $this->objectCopyService->copyFieldsetToTarget(
                'order_address',
                'to_customer',
                $order->getBillingAddress(),
                []
                );



        $addresses = $order->getAddresses();
        foreach ($addresses as $address) {
            $addressData = $this->objectCopyService->copyFieldsetToTarget(
                    'order_address',
                    'to_customer_address',
                    $address,
                    []
                    );

            /** @var \Magento\Customer\Api\Data\AddressInterface $customerAddress */
            $customerAddress = $this->addressFactory->create(['data' => $addressData]);
            switch ($address->getAddressType()) {
                case QuoteAddress::ADDRESS_TYPE_BILLING:
                    $customerAddress->setIsDefaultBilling(true);
                    break;
                case QuoteAddress::ADDRESS_TYPE_SHIPPING:
                    $customerAddress->setIsDefaultShipping(true);
                    break;
            }

            if (is_string($address->getRegion())) {
                /** @var \Magento\Customer\Api\Data\RegionInterface $region */
                $region = $this->regionFactory->create();
                $region->setRegion($address->getRegion());
                $region->setRegionCode($address->getRegionCode());
                $region->setRegionId($address->getRegionId());
                $customerAddress->setRegion($region);
            }
            $customerData['addresses'][] = $customerAddress;
        }
        $account    = $this->createUser($customerData, $websiteId, $storeId, (int)$this->getRequest()->getParam('group'), $count);

        $order
        ->setCustomerId($account->getId())
        ->setData('customer_group_id', $account->getGroupId())
        ->setData('customer_is_guest', 0)
        ->setData('customer_firstname', $account->getFirstname())
        ->setData('customer_lastname', $account->getLastname());

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

    }

Nits
  • 2,496
  • 1
  • 8
  • 21
  • Thanks for the answer, but can we use "$this->orderCustomerService->create($orderId);" to convert guest to customer ? – Hamendra Sunthwal Mar 15 '21 at 10:44
  • I can see that magento uses "$this->orderCustomerService->create($orderId);" to convert guest to customer. – Hamendra Sunthwal Mar 15 '21 at 10:44
  • @HamendraSunthwal I just gave you the reference code, how to implement that is up to you. :) Please let me know if you need more details. :) – Nits Mar 15 '21 at 10:46
0
<?php
namespace Vendor\Module\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\Customer;
use Magento\Customer\Api\AccountManagementInterface;
use Vendor\Module\Helper\Data;

class InstallData implements InstallDataInterface {
    private $eavSetupFactory;
    protected $customerFactory;
    protected $_pageFactory;
    protected $loginHelper;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        Config $eavConfig,
        CustomerFactory $customerFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        AccountManagementInterface $customerAccountManagement,
        Data $helper
    ) {
        $this->customerAccountManagement = $customerAccountManagement;
        $this->storeManager = $storeManager;
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig       = $eavConfig;
        $this->customerFactory = $customerFactory;
        $this->loginHelper     = $helper;
    }

    public function install( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) {
        $eavSetup = $this->eavSetupFactory->create( ['setup' => $setup] );
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'is_admin',
            [
                'type'         => 'int',
                'label'        => 'is_admin',
                'required'     => false,
                'visible'      => false,
                'position'     => 999,
                'default'      => 0
            ]
        );
        $sampleAttribute = $this->eavConfig->getAttribute( Customer::ENTITY, 'is_admin' );

        $sampleAttribute->setData(
            'used_in_forms',
            ['adminhtml_customer']
        );
        $sampleAttribute->save();

        $configEmail = $this->loginHelper->getConfigEmail();
        $websiteId = ( int )$this->storeManager->getWebsite()->getId();
        $isEmailNotExists = $this->customerAccountManagement->isEmailAvailable( $configEmail, $websiteId );

        if ( $isEmailNotExists == true ) {
            $data = [
                'firstname' => 'admin',
                'lastname' => 'admin',
                'email' => $configEmail,
                'password'=>'abc123456',
                'is_admin'=>'1'
            ];

            $this->customerFactory->create()->setData( $data )->save();
        }
    }
}
aich.khalid
  • 375
  • 1
  • 13