1

I am trying to assign a group from currently logged in user(One group in assigned only) to a newly created individual.

function search_civicrm_post($op, $objectName, $objectId, &$objectRef){ {

$getContactId = (int) CRM_Core_Session::singleton()->getLoggedInContactID();

try {
    $result = civicrm_api3('GroupContact', 'getsingle', [
        'return' => ["group_id"],
        'contact_id' => $getContactId,
    ]);
} 
catch (CRM_Exception $e) {
    echo "error";
}

$getGroupId = $result['group_id'];
$recentContactId= '';
$query ="INSERT INTO `civicrm_group_contact` (`group_id`, `contact_id`, `status`) VALUES ('.$getGroupId', '$recentContactId','Added')";

But problem is that how will I get the id of recently added individuals;

1 Answer 1

3

If I understand it correctly you want to add contact (New individual) to a group of logged in user, then i would write something like this

function search_civicrm_pre($op, $objectName, $id, &$params) {
  if ($objectName == 'Individual' && $op == 'create) {
    $groups = civicrm_api3('Contact', 'getsingle', [
      'return' => "group",
      'id' => 'user_contact_id',
    ])['groups'];
    foreach (explode(',', $groups) as $groupId) {
      $params['group'][$groupId] = 1;
    }
  }
}

HTH

Pradeep

12
  • Hello Pradip Sir, I successfully fetch the group id of currently logged in contact(Only one group is there). When I am adding a new Individual it must attach a group of currently logged in contact. How can I do that? I am not getting a solution.
    – Dipak Giri
    Commented Jan 8, 2019 at 10:41
  • Did you try above snippet? Commented Jan 8, 2019 at 10:43
  • Yes. Give an error "field group unset or not existing"
    – Dipak Giri
    Commented Jan 8, 2019 at 10:49
  • 1
    I have updated the code, Try the updated snippet Commented Jan 8, 2019 at 11:16
  • 1
    pre() hook is used to alter the params which is used for creating a contact. You can pass additional params likes groups, tags etc since the BAO handles it correctly. In short pre() hook is invoked just before a contact is created and post after a contact. Commented Jan 8, 2019 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.