Using 'Event Subscriber', I'm able to get $order and $items from the order after completing the checkout.

How can I get the product id from the $itemsand modify the product custom field value?

Scenario: I want to change the status of the product after completing the first checkout of that product.

1 Answer 1


Do you really want to change the status of the product or the product variation?

$items is an array of OrderItems. If you loop over the items, you can get the referenced purchased entity of the single item with $purchasedEntity = $item->getPurchasedEntity();. If you only want the first item you can access it like so $purchasedEntity = $items[0]->getPurchasedEntity();. In case the PurchasedEntity is a ProductVariation you can get the product with $product = $purchasedEntity->getProduct();

In case you want to change the status of the product:


Or for the variation:


If you want to set any custom field on the product variation:

$variation->set('your_custom_field_name', $value);

docs This assumes you use the default commerce2 product architecture. It is absolutly possible that you get other purchasable entities than ProductVariations back from the OrderItem.

  • I have one 'select' field and i have to change the value of that. doesn't required to make product unpublished. Example: 'status' select field which has 'active and deactive'. I want to change to 'deactive' after checkout of this product.
    – shanidkv
    Dec 6, 2017 at 8:07
  • Updated the answer for setting custom fields. Here is the [doc] (api.drupal.org/api/drupal/…) Dec 6, 2017 at 8:33
  • Thanks!! Let me try below code. $purchasedEntity = $item->getPurchasedEntity(); $product = $purchasedEntity->getProduct(); $product->set('field_custom', 'updated..');
    – shanidkv
    Dec 6, 2017 at 8:40
  • Getting Fatal error: Call to a member function getPurchasedEntity() on null error. Can you help me to resolve.
    – shanidkv
    Dec 6, 2017 at 15:07
  • You're welcome :D. Improved the answer for future reference. It should be more clear now, that one have to loop over the items or how one can access the first item directly. Dec 7, 2017 at 8:31

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.