2

I have one 'select' field in product page it has value 'Open', 'Closed'.I want to changed to 'Closed' after completing the first order of this product.

There is one issue which someone answered for Drupal 7 and it is done by using 'Rules' module. How I can change the value of a commerce product field after Completion process?

How I can do that using Hooks and without Rules module?

EDIT: I feel we can use below hooks. But how we can find the product and change the custom field value of the product?

function hook_commerce_checkout_complete($order) {
  if($order->status == 'completed') { 
  }
} 

hook_commerce_checkout_complete

EDIT 2:

Got the solution for Order Complete event - https://medium.com/@sumanthkumarc/writing-event-subscriber-for-order-complete-event-in-drupal-8-commerce-2-x-196292330b1c. Now question is How I can modify the product custom field value?

public function orderCompleteHandler(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();
  $items = $order->getItems();
}

How can i get the product id from the order items and change the custom field(field_prodstat) value

0

You'll want to use the commerce hook_commerce_checkout_complete which runs after a order is complete (AKA paid for)

http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21checkout%21commerce_checkout.api.php/function/hook_commerce_checkout_complete/7

That provides the order and you'll just need to get the product ID from that $order variable, load it with product_load(), change the value you want and then save

  • That's for Commerce 1; Commerce 2 got rid of hooks in favour of events – Clive Nov 27 '17 at 15:59
  • Ah sorry missed the commerce 2 in the title – Leigh Nov 27 '17 at 16:21
0

1) Use Event Subscriber for 'Order Complete' event.

2) You can get the purchased product from the $order and use below code to update product custom field.

public function orderCompleteHandler(WorkflowTransitionEvent $event) {

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  // Order items in the cart.
  $items = $order->getItems();

  //I just hard coded index. You can write foreach loop for getting multiple products. 
  $purchasedEntity = $items[0]->getPurchasedEntity(); 

  $product = $purchasedEntity->getProduct();
  $product->set('field_custom_field', 'Updated field');      
  $product->save();

}

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.