I'm working on a module which is going to be used alongside Drupal Commerce so people can buy a set number of digital products. I've written a custom rules action, which will be run once for each purchase of a specific commerce product. How can I add this to a loop, so that the action gets run n times (n being the quantity purchased for this product, as you could purchase more than one).

So far I've added this action to a loop for commerce-order:commerce-line-items but even if I purchase more than one, the action is only run once. How can I make the action run 'quantity of this product purchased' number of times?

Many thanks

1 Answer 1


The quickest way to do this is with another custom action. Since you already wrote your own module, this shouldn't be a problem.

In your my_module.rules.inc file, do something like:

function my_module_rules_action_info() {
 return array(
  'my_module_loop_based_on_qty' => array(
    'label' => t('Execute a loop based on a quantity'),
    'parameter' => array(
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity added to cart'),
    'group' => t('My Module'),

function my_module_loop_based_on_qty($qty) {
  // Loop based on the $qty variable

Provide whatever other parameters you need for the function as well. You can then pass it the quantity when you create the rule. That other rules action you already wrote can just be wrapped in a helper function that is then called by this new action.

  • This looks like a good approach. Would this mean that I would add the action to rules without a loop (as I can just perform operations with the quantity value in my module)? Commented Aug 22, 2013 at 14:19
  • That is correct. Just run your loop in the module code. You'll just also need to pass the function from the Rules whatever you need to loop over.
    – jazzdrive3
    Commented Aug 22, 2013 at 14:33
  • In Rules, I've added the new custom Action and it's asking me for a data selector and an offset. How would you work with this setup? (Sorry, I'm still learning the ropes with Rules) Commented Aug 22, 2013 at 14:39
  • The data selector will be the token that contains the quantity, just like any other token in rules. You can ignore the offset.
    – jazzdrive3
    Commented Aug 22, 2013 at 14:59
  • I think the key for me is to learn more about Rules in general. I've managed to get this working by looking at how the stock management module works and learning from that (as this performs calculations using the quantity). Many thanks for your help. Commented Aug 27, 2013 at 9:03

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.