Commerce 1.x (D7) has a hook _commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) that allows modules to add arbitrary AJAX commands to the array returned from the Add to Cart form attributes refresh. Is there anyway to have something similar in Commerce 2.x (D8)?. I would like to add my custom commands.

1 Answer 1


Drupal 8/9 modules often use events to take the place of alter hooks like this one found in Commerce 1.x on Drupal 7. You have to do a little digging to find the place in the code that executes it, but you can look it up with the following info:

  1. An Add to Cart form in Commerce 2.x is an order item add form governed by the "Add to Cart" form mode (a new concept in Drupal 8).
  2. Looking at the configuration for the default order item type, you can see that the "Purchased entity" reference field uses a field widget called "Product variation attributes."
  3. You can find that widget's definition in the ProductVariationAttributesWidget.php plugin contained in the product module, and its formElement() function shows you that it invokes an ajaxRefresh() function on the object to process the Ajax response when attributes are updated.
  4. That class extends ProductVariationWidgetBase where the ajaxRefresh() function is located. You can see that it builds a response array using an Ajax renderer and gives other modules the opportunity to add commands to the response array via the PRODUCT_VARIATION_AJAX_CHANGE event (using a constant defined in the ProductEvents.php class).

If you're still following, the solution then is to create your own event subscriber that subscribes to that event and appends your own commands to the event's $response array. I've created an example module showing how to do this: https://github.com/rszrama/commerce_example3

  • 1
    Thank you very much for your answer and your example. It's just what I was searching.
    – briast
    May 31, 2020 at 14:17
  • 1
    Thank you for the example which still works in 2024. Apr 10 at 8:59
  • Hah, excellent. Happy to help! Apr 11 at 12:24

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.