1

I have followed Create order programmatically in Magento 2

But it is saving the customer.

And When I skip customer set data and customer save then It's getting an error report like

"Please enter customer email".

Any thoughts ??

3

2 Answers 2

7

The above answer is correct but the standard way is not to create the Customer in case of Guest Checkout.

            $cartId = $this->cartManagementInterface->createEmptyCart();

            /** @var \Magento\Quote\Model\Quote $quote */
            $quote = $this->cartRepositoryInterface->get($cartId);

            $guest = true;
            if ($guest) {
                // Set Customer Data on Qoute, Do not create customer.
                $quote->setCustomerFirstname("Guest First Name");
                $quote->setCustomerLastname("Guest Last Name");
                $quote->setCustomerEmail("[email protected]");
                $quote->setCustomerIsGuest(true);
            } else {
                // Create customer object and assign to qoute 
                /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
                $quote->assignCustomer($customer);
            }

Also, the best place to check the sample code for anything to do programmatically is in Magento Integration test cases present in dev/tests/integration/testsuite/.

https://github.com/magento/magento2/tree/2.3-develop/dev/tests/integration/testsuite/Magento/Sales/_files

2
  • where do you get the customer-object from? Do you have to create is completely new?
    – codiga
    Sep 3, 2020 at 15:52
  • @codiga that is else case, for customer order. Sep 3, 2020 at 16:19
2

You can check below blog for create order programmatically, I have given full demo for create order in Magento 2, Check link, Create Order Programmatically

You need to skip Customer create step, In above blog, YOu need to replace,

if(!$customer->getId()){
            //For guest customer create new cusotmer
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderInfo['address']['firstname'])
                    ->setLastname($orderInfo['address']['lastname'])
                    ->setEmail($orderInfo['email'])
                    ->setPassword($orderInfo['email']);
            $customer->save();
        }

with,

if(!$customer->getId()){
    //For guest customer create new cusotmer
    $customer->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname($orderInfo['address']['firstname'])
            ->setLastname($orderInfo['address']['lastname'])
            ->setEmail($orderInfo['email'])
            ->setCustomerIsGuest(1);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.