I know how to load an order by its ID using \Drupal\commerce_order\Entity\Order::load($order_id). I added a custom field (Token ID) to the orders.

How can I load the orders knowing the value of that field? If I want to get the state of the order, how can I achieve it?

  • Is that custom field added field from managed Fields or you just programmatically adding it? – Ajay Reddy Aug 20 '18 at 7:39
  • I added field from manage fields. Field name "field_token_id". – Rifas Ali Aug 20 '18 at 7:41

The best way to do this is by using by loadByProperties based on Token field:

$orders = \Drupal::entityTypeManager()
  ->loadByProperties(['field_token_id' => 'TOKEN VALUE']);
$order = reset($orders);
$state = $order->get('state')->value;
$total_price = $order->getTotalprice()->getNumber();
$currency = $order->getTotalprice()->getCurrencyCode();

Here assuming token as a unique value.

  • Similarly I tried to get total price by $total_price = $order->get('total_price')->value; but it doesnt work. But when i use $order-getTotalprice(); i am getting price with currency code. What should i type if i just want the number/price.? – Rifas Ali Aug 20 '18 at 8:14
  • Updated answer. – Ajay Reddy Aug 20 '18 at 8:51
  • Did you know how to solve this ? drupal.stackexchange.com/questions/269311/… – Rifas Ali Sep 14 '18 at 5:30

you will need to use Drupal EntityQuery to get the order id and load order using its id, the following code might help :

$query = \Drupal::entityQuery('commerce_order')
->condition('field_token_id.value', VALUE_OF_TOKEN);
$order_ids = $query->execute();
foreach($order_ids as $order_id) {
  • Thanks... :) Yes.. I am able to load the order. I am getting an array. Now how can i get each field in that corresponding order. Suppose i want to store "signature_id" in a variable which is also a custom field in that order. How can i get that. – Rifas Ali Aug 20 '18 at 8:06
  • @RifasAli I edited the above code to show how you can get the order state. I prefer the use of entityQuery to the entityTypeManager mentioned above since it is a bit simpler. – ahimsauzi Jun 26 '19 at 20:44

I believe the Most efficient and Fast way to get all the Orders is

$orders = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadMultiple();

if you want to get the Completed Orders then you can use the loadByProperties() as like:

$orders = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadByProperties(['state' => 'completed']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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