13

I display the summary page for a civicrm contact and I need to get the current contact id. Is there any built in function for that?

I have this code where I explicitly refer to the civicrm id 4. Instead of doing that I would like to refer to the current civicrm contact.

$contact_id = 4;
$custom_name = array("custom_2","custom_3","custom_6","custom_7");
$params = array(
        'return' => $custom_name,
        'version' => 3,
        'id' => $contact_id,
);

$result = civicrm_api( 'contact','get',$params );
9

If you are on the contact summary screen, then the contact id is always $_GET['cid']. To give yourself peace-of-mind about using raw input, cast it to an integer.

$contactId = (int) $_GET['cid'];
  • 5
    You could also do this with $contactId = CRM_Utils_Request::retrieve('cid', 'Positive'); – ErikH - CiviCooP Jul 10 '15 at 9:03
  • 3
    I think Erik's should be a separate answer and the only correct one. Coleman, really! – Alan Dixon Jul 14 '15 at 20:14
15

The answer davejenx is correct but no longer considered best practice. Instead use:

CRM_Core_Session::singleton()->getLoggedInContactID();
  • Thanks Jon. Which Civi versions implement this method? – davejenx Jul 5 '16 at 12:41
  • It's in 4.4+, maybe earlier versions too? – Jon G - Megaphone Tech Jul 5 '16 at 20:45
6

Edit: The techniques below get the logged-in user's contact id. However the questioner has clarified that this isn't what they meant by "the current contact id". I'll leave this answer in place in case it's useful to someone else who misunderstood the question. Here's a simple way:

CRM_Core_Session::singleton()->getLoggedInContactID();

The above (for which thanks to Jon G) replaces this older technique:

$session = CRM_Core_Session::singleton();
$contact_id = $session->get('userID');

You can also do it by getting the user id from the CMS (Drupal / Wordpress / Joomla), then using the CiviCRM API to get that user's UFMatch record, which gives you the contact id.

  • I use wordpress. Do you know how to return the current contact_id in wordpress? – Csaba Jul 9 '15 at 14:01
  • This will return MY wordpress username's ID but I need the currently displayed contact's civicrm ID :) – Csaba Jul 9 '15 at 14:07
  • Like davejenx said: use the Civi API UFMatch Get (with uf_id = the wordpress username's id), it will return you the contact_id. – ErikH - CiviCooP Jul 9 '15 at 14:30
  • Ah, I misunderstood what you were trying to do. In that case, see Coleman's answer. – davejenx Jul 9 '15 at 14:46
  • 1
    This is no longer considered best practice, see my answer. – Jon G - Megaphone Tech Jul 4 '16 at 16:50

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.