I am setting up a default rule for my custom Drupal 7 module, as follows:

  array('something' => 'something_else'))
    'message' => t('Example message'),

I have written a function, mymodule_condition_1, which returns TRUE or FALSE based on what product is being added to the cart. I need to be able to get the product from the rules event, and pass this to the condition. I have looked through all the documentation and example code but I can't seem to see a way to do this.

In the above example, 'something' and 'something_else' need to be specific values, but I can't see what I can refer to in order to find out what they should be.


In a case like this, you'd going to have to use what Rules calls a data selector. If you were building this Rule through the UI, you would click the "Switch to data selection" and enter some token that corresponds to the type of parameter required. In this case, the commerce_cart_product_add event provides the arguments commerce_order, commerce_product, quantity, commerce_line_item, and commerce_line_item_unchanged. (See all this in the event's definition in commerce_cart.rules.inc.) So when trying to select the product passed to the event through the UI, you'd use commerce-product as the value for your condition's product parameter.

When building this Rule in code, you specify a data selector by appending :select after your condition's parameter's name. So, if the name of the product parameter for your condition (as defined in hook_rules_condition_info()) is commerce_product, your "something" would be commerce_product:select. The "something_value" would be the same token you'd enter through the UI, commerce-product (as that's the name of the product argument passed to the Rule).

And touching on one more aspect, the event info defines the variables that must be passed to Rules when an event is invoked. Your condition can use any, none, or all of these - it doesn't really matter. A condition or action's definition simply states what kind of parameters it needs, and the Rule configuration is responsible for passing the parameters to the condition from the pool of available variables (or from variables you load as part of the configuration).

  • Thanks, I was missing the bit in my condition that tells rules what parameters I want to accept. So, I had told it which bit of the event's parameters I wanted to use, but the condition was not aware I wanted to use it. This answer really helped! Jul 8 '11 at 16:33

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.