drupaldrupal-7drupal-commerce

How to add new rules in drupal


I'm trying to add some rules programmatically, I'm following this tutorial to manage different price list depending of the rules. To create the rules it usesa default_rules_configuration hook which will be executed "when the rules will be loaded".

1 - It's not really clear, when "rules are being loaded", apparently running the cron do it. Is it the only way to trigger it ?

2 - Is there a way to add rules programmatically, so rule can be added in the insert role hook, or is this default_rules hook the only way to do it ?

Thanks


Solution

  • 1 - According to hook_default_rules_configuration() documentation:

    This hook is invoked when rules configurations are loaded.

    The function is actually called when you clear your cache as this is when Drupal rebuilds the default entities provided in code through entity_defaults_rebuild().

    You can examine the full call stack as to how hook_default_rules_configuration function is called using debug_backtrace()

    2 - To set a rule that reacts on inserting a role, you actually have to create a rule that reacts on a user insert action and then check the role saved to see if it matches the role that you're interested in reacting to.

    I find it easier to do this via the UI. Here's an export of a rule that checks to see if the user is assigned the anonymous role and sends an email to admin if so:

    { "rules_role_change_rule" : {
        "LABEL" : "Role change rule",
        "PLUGIN" : "reaction rule",
        "REQUIRES" : [ "rules" ],
        "ON" : [ "user_insert" ],
        "IF" : [
          { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "1" : "1" } } } }
        ],
        "DO" : [
          { "mail" : {
              "to" : "admin@website.com",
              "subject" : "User role changed",
              "message" : "User role has changed",
              "from" : "drupal@website.com",
              "language" : [ "" ]
            }
          }
        ]
      }
    }
    

    You would still have to implement hook_default_rules_configuration but replace the rule in the tutorial with one that suits your needs.