Score:0

Programmatically getting variation type fields in order

ao flag

I am trying to get variation type field values from the order entity but I can't find any documentation on this. I am using an event subscriber to run the following code when an order is paid. The code works, but I can't see any reference to the fields in kint and I can't find any references to any kind of "getVariation" or equivalent function online.

/**
 * This method is called when the commerce_order.order.paid is dispatched.
 *
 * @param \Symfony\Component\EventDispatcher\Event $event
 *   The dispatched event.
 */
public function commerceOrderOrderPaid(Event $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getOrder();
  $items = $order->getItems();
  foreach ($items as $item) {
    kint($item);
    if ($item->get('type')->target_id == 'purchase_things') {
      // 'number_of_things' is a variation type field.
      $thingQuant = $item->get('number_of_things'); 
      // The line does not work, obviously. 
      // I cannot see 'number_of_things' anywhere in kint($item).
    }
  }
}
Score:1
ao flag

Using Devel and Kint I was able to find the "getVariation" function I was looking for. This code lets you get the variation type fields.

$item->getPurchasedEntity()->get('field_number_of_things')->value

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.