Score:1

How do I programmatically create an order without deleting a profile?

eg flag

I followed Orders to write the following code.

$order = \Drupal\commerce_order\Entity\Order::create([
  'type' => 'custom_order_type',
  'state' => 'draft',
  'mail' => '[email protected]',
  'uid' => 1,
  'ip_address' => '127.0.0.1',
  'order_number' => '6',
  'billing_profile' => $profile,
  'store_id' => $store->id(),
  'order_items' => [$order_item],
  'placed' => time(),
]);

$profile is a user profile.

I then programmatically change the order status to place with $order->getState()->applyTransitionById('place');.

The order is placed and everything looks fine, except that the user addressbook becomes empty. I think I miss a step.

Is there a way to preserve the addressbook while placing the order?

Score:3
it flag

The profile is not being deleted - it's just becoming "owned" by the order. This occurs in Order::preSave() where the profile uid is set to 0. This ensures that a customer will not be able to use the addressbook interface to edit a profile referenced by an order. For more background on how the addressbook in Commerce 2.x works with respect to profile copying, please see may article:

https://www.centarro.io/blog/understanding-drupal-commerce-2x-address-book

The solution is for you to create a copy of the profile yourself, set its uid to 0, and reference that profile from your order instead of the original one.

Aves2432 avatar
eg flag
Thank you, this solves my issue
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.