Programmatically disable a rule

Public
</> CopyGet raw version
php
  1. /**
  2. * Implements hook_update_N().
  3. * Disables name_of_rule rule.
  4. */
  5. function hook_update_N() {
  6. $rules_config = rules_config_load('name_of_rule');
  7. $rules_config->active = FALSE;
  8. $rules_config->save();
  9. }

Comments

Tyler Frankenstein's picture

FYI, when I was logged out of this site, it showed the function call as `rule_config_load` instead of `rules_config_load`, very strange.

UPDATE - but after I posted this comment, and then visited the page as an anonymous user, the page was refreshed to the proper code. Perhaps a caching bug with this site...?

Tyler Frankenstein's picture

Here's some helper functions you can use to enable disable a Rule:

  1. /**
  2.  * Given a Rule's machine name, this will enable the Rule.
  3.  */
  4. function my_module_enable_rule($rule_machine_name) {
  5. _my_module_rules_set_active($rule_machine_name, TRUE);
  6. }
  7.  
  8. /**
  9.  * Given a Rule's machine name, this will disable the Rule.
  10.  */
  11. function my_module_disable_rule($rule_machine_name) {
  12. _my_module_rules_set_active($rule_machine_name, FALSE);
  13. }
  14.  
  15. /**
  16.  * Given a Rule machine name, and an boolean will set its active or not.
  17.  */
  18. function _my_module_rules_set_active($rule_machine_name, $active) {
  19. $rules_config = rules_config_load('rules_' . $rule_machine_name);
  20. $rules_config->active = $active;
  21. $rules_config->save();
  22. }

Then you can enable a Rule like so:

my_module_enable_rule('rules_name_of_rule');

And disable it like so:

my_module_disable_rule('rules_name_of_rule');

Keep in mind that it appears the Rules module prefixes the machine name with 'rules_'.

Josue Valencia's picture

i got this when i tried to run the update.php

ResponseText: Fatal error: Call to undefined method stdClass::save()

what is this doing: $rules_config->save();
?

the "soloution" was simple:
$rules_config = rules_config_load($rule_machine_name);
dont put the 'rule_' before the machine name, it is not neccesary