Emailing all users that flagged a node using Rules in Drupal 7

Emailing all users that flagged a node using Rules in Drupal 7

Drupal’s Flag module can be awesome in many situations. I’ve recently used it on a site to allow users to receive an alert when an ‘out of stock’ ubercart product is re-stocked and ready for purchase again. The process was pretty easy.

Part one was the ‘flagging a product’ part. Flag easily handles this so a user can flag any node on which they want to receive updates. Easy enough.

Part two was the ‘emailing the user’ when the stock level went from 0 to >0. Unfortunately, ubercart does this in few places so I had to hook into each one and create a custom event (so the client can easily configure/update the email which is sent). The custom event simply passes the node that is now back in stock and the Rule takes care of the rest.

Take away ubercart and looping through all the users of a flagged node is very simple. If the node entity is available, there is an option to retrieve a list of users that flagged the node (you will have to select which flag since you could be using multiple flags on a single node).

Below the an export example with the loop and mail part.

{ "rules_product_back_in_stock_alerts" : {
    "LABEL" : "Product back in stock alerts",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mymodule_product_alerts" ],
    "ON" : { "mymodule_product_alerts_product_in_stock" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:flag-product-in-stock-alert-user" ] },
          "ITEM" : { "user_entity" : "Current user" },
          "DO" : [
            { "mail" : {
                "to" : [ "user-entity:mail" ],
                "subject" : "[node:title] is back in stock at [site:name]",
                "message" : "[node:title] is available for purchase - [node:url]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Comments are closed.