Drupal7: civicrm_rules - Add/Remove contact from CiviCRM Group works with deprecated method on removal
Problem/Motivation
In the the civicrm_rules module, specifically drupal/modules/civicrm_rules/civicrm_rules_utils.inc
and on line 64 there's this function _civicrm_rules_group_contact
that by default uses the 'create' action if we want to add a contact into a CiviCRM Group which works absolutely fine.
However, when we want to delete a contact, this is what is initially being called:
civicrm_api('group_contact', 'delete', $params);
which I believe as an action it is now considered as deprecated and (most probably because of that), it's behaving weird:
It will remove a contact from a static group, but it will not remove a contact from a smartgroup.
Steps to reproduce
Create a rule so that it has an action that will remove an existing CiviCRM contact from a group on webform submission (or something related to that).
Outcome:
- Rule will apply and contact will be removed if that group that he belongs to is a static group
- Rule will not apply and contact will not be removed if that group that he belongs to is a smartgroup
Proposed resolution
Current function:
/**
* Function to add contacts to group
*/
function _civicrm_rules_group_contact($contactId, $groupId, $action = 'create') {
civicrm_initialize();
$params = array(
'contact_id' => $contactId,
'group_id' => $groupId,
'version' => 3,
);
// This used to be civicrm_group_contact_common($params, $action);
civicrm_api('group_contact', $action, $params);
}
Proposed change:
/**
* Function to add/remove contacts to group
*/
function _civicrm_rules_group_contact($contactId, $groupId, $action = 'create') {
civicrm_initialize();
$params = array(
'contact_id' => $contactId,
'group_id' => $groupId,
'version' => 3,
);
if ($action == 'delete') {
$params['status'] = 'Removed';
}
// This used to be civicrm_group_contact_common($params, $action);
civicrm_api('group_contact', 'create', $params);
}
Basically we keep the action as 'create' and then we intercept the incoming $action variable.
If it has the 'delete' value, we add to the $params the 'status' = 'Removed' so that it can remove it.
I tried that fix and it works for me but i would ask you to replicate it in your environment(s) as well.