This documentation relates to CiviCRM version 3.2. It's not maintained anymore.
Current version of documentation.

Using CiviCRM APIs - Code Snippets

Skip to end of metadata
Go to start of metadata

This page refers to outdated version of CiviCRM. Check current version of documentation.


Documentation Search


CiviCRM 3.2 Documentation

Support and Participation

Developer Resources


CiviCRM book!

Make sure to check out Understanding CiviCRM as well! You can also support this project by ordering a hard copy.

Contents
API Code Snippets

Please add code snippets to this page which use/invoke CiviCRM APIs. Section titles should indicate the API(s) used when possible. Additional examples of API usage can be found by browsing the CiviCRM API test files in the SVN repository: test cases.

Getting Started with Standalone Scripts

For standalone php scripts to gain access to all APIs you must follow a few steps.
First you will need to include the following files:

  1. civicrm.settings.php (remember where you put this during installation)
  2. $civicrm_root/CRM/Core/Config.php
  3. include specific php files within the api directory

After including the civicrm.settings.php file you can get the $civicrm_root via the php "global" directive.

Once you have the  header files included you must initialize CiviCRM.  I've seen many ways to do this, but my favorite is:

Now you can enjoy making all the API calls you want! Example (for drupal modules)

Hello World

The following is a complete stand-alone script that outputs a list of all contacts that have the email address johndoe@email.com.

Note: This script does not initialize CiviCRM or the user framework, as you will typically want to do with most API applications.

Display a sorted list of group members in a Drupal block using civicrm_contact_search

  • Create a new block and set Input Format to PHP code.
  • Adjust the code snippet below:
    • Replace $myGroup value with the name of your group;
    • Add or remove return properties from params array and $string in the display section, depending on what info you want to include;
    • Modify the sort criteria in params array if desired (the code currently specifies ascending sort on the CiviCRM sort_name property which is last_name, first_name for Individuals, or organization_name, or household_name).

Note that the API by default returns only the first 25 records found. To return more add this parameter to $params:

to retrieve 100 records for example.

Retrieve info for a contact with a given email address using civicrm_contact_search

Insert an activity history record for a contact - including callback and activity identifier

This snippet inserts an activity history with a callback function and identifier (key). The callback plus identifier will generate a Details link when the contact's activity history is displayed - and the link should invoke a function (either w/in CiviCRM or a remote module) which can display details about the activity.

List Public Events by Event Type in a Block

This snippet uses the v2 (new-style) Event Search API. The example code will run as-is in a Drupal block which has format set to PHP code. Note that the specific v2 API - Event.php is included up front.

Here is a similar example, but this provides link to the event registration pages and makes sure an event is set as active and public (and doesn't restrict by event type). NOTE: This example uses the Drupal 5 l() function to output the $display. There is a line commented out above that you would reverse if you are using it with Drupal 6. This also provides display for events with date ranges:

Assign users to CiviCRM groups based on their role(s)

This code snippet was contributed by Rich Orris of CivicActions. It is part of a module - so you may need to adjust things for your usage but it provides a good example of how to accomplish this.

Check status of an email address entered on a custom subscription form.

This snippet was contributed by Josh On.

Create scripts based on profile and user data (filtering users through profiles)

A common activity of add-on modules is preparing online scripts that include data about the person reading/using the script and the person receiving the information. Use case examples might include phone banking for political campaigns, cold calls for sales staff, and other situations where an administrator wants to present a consistent, but personalized, block of text.

Scripts are a specific case of the more general need to filter user data through profiles. As most users interact with CiviCRM by filling out data in profiles, using profiles to do scripting is a natural choice. The trick is matching the fields in a profile with the actual data stored in the CRM.

These functions, from the CiviContact module, provide the basic scripting support: creating tokens, matching user data to profile fields, and replacing tokens in a script.

Step 1: Create the tokens

The first step of creating a script, is creating a list of available tokens. This tokenizer accepts a profile id, loads the profile data, and spits out a list of tokens a module can present to a user creating a script.

Here is some example code about how this might be used (taken from CiviContact, with appropriate name changes):

Step 2: Match profile fields to user data

So, our user has created a script. At some time in the future, we are going to need to interpret that script. The first step of this process is finding the data we need for each profile field. Here is my solution, though there are probably many others. Note this requires a slight hack: making a call directly into the CiviCRM core. Some API purists may dislike this. I know I do. (wink)

Step 3: Replace tokens with actual data

Now that we have a mapping from profiles to user data (step 2) we can replace the tokens we created (in step 1). Given that you still have the appropriate profile ID stored, this is not a very difficult task. After filtering a user by his/her profile data, you can just replace each profile key with the equivalent token and then do a quick "untokenizing" process.

Here's some more sample code that ties steps 2 and 3 together.

Some other common Drupal tasks

A form selection box that honors permissions set in Drupal Access Control

The CiviCRM drupal module allows admins to limit user access to specific groups. This code snippet allows users to select from their allowed groups. If a default group is passed into the function that the user does have access to, it is added to the list. This "feature" is easily stripped out if you don't want this behavior.

Get a CiviCRM user object

You will often have to get the civicrm user record for a user in Drupal land. (<em>I should update this to include optional user syncing...</em>)

Use theme_username along with Contact and UFGroup APIs to replace username with First and Last Name pulled from CiviCRM

Reminder: Theme functions are usually placed in your template.php file.

Display the number of users in a group, including smart groups

  • Create a new block and set Input Format to PHP code.
  • Adjust the code snippet below:
    • Replace $myGroup value with the name of your group;
    • Replace $myPrecision to 0 if you want the exact number of users, 1 to truncate to the tens, 2 to truncate to the hundreds, 3 to truncate to the thousands, etc... useful for displaying "More than X users"...
    • Add HTML code before or after the code snipet, or modify the print $num line to include your HTML.

Display cumulative gift totals in date range

  • I run this code in a PHP page, and copy/paste the CSV output into an .xls or .txt document.

display cumulative gift totals in date range

I run this code in a PHP page, and copy/paste the CSV output into an .xls or .txt document.

Display a list of recent contributors

This displays a list of recent contributors.

Display list of premiums that need to be fulfilled

This is a way to make a page in drupal that has a list of the premiums that need fulfillment. You'll need to make your own call backs via the hook_menu and probably protect them with hook_perm as well.

Display list of upcoming birthdays

This display a list of the birthdays in the next 7 days, with a link to the contact pages.

Create Event Listing Page (based on Event Block code)

see  http://jicny.com/events for an example. Includes a registration button if the event is registered.  It can be adapted for newsletters that include events.Uses CSS extensitvely to customize. Please feel free to suggest improvements!

Updating employer data in civicrm_contact

This code is part of a routine o update the employer data in the file civicrm_contact. In this specific example, I have a large import file containing data from a legacy system in a separate MySQL table.

I take 2 steps to create the contact data in CiviCRM, because I need to build relationships so I have to have the civicrm contact_id. I store this in the source table during my first read.

When I build the relationships, I also update the employer data in the contact file:

Example of conversion using API's (contact, group, location, relationship, note)

The situation: I have an import .csv file coming from an Oracle application, which I want to import into CiviCRM. The client I did this for used relationship types, custom data, notes and groups. I used a basci class for contacts and extended classes for individuals and households. The API's are called from within the classes. The example here shows the basic class for contact CiviContact, and the one for persons CiviPerson. I also created a configuration script so the same setup can be used in different environments. In this script the error handling is set, the constants used are defined, CiviCRM is initialised and the required API's are included.

Questions? Give me a shout : hommel@ee-atwork.nl! By the way....all comments are in Dutch :-)

The basic class CiviContact:

The class for Individual CiviPerson, which also migrates some custom data:

Labels
  • None

Creative Commons License
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-Share Alike 3.0 United States Licence.