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
  • It clearly said that we need to set the customer for the guest order. Commented Nov 1, 2018 at 3:10
  • @khoa, So I should remove the customer save script only to make it work as guest checkout Commented Nov 1, 2018 at 11:07
  • Please refer siphor.com/programmatically-create-an-order-in-magento-2 this link. I try this and it's working fine for me. Commented Nov 7, 2019 at 5:36

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? Commented Sep 3, 2020 at 15:52
  • @codiga that is else case, for customer order. Commented 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); } 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.