|
Contents
|
 | CiviCRM 2
Please note that the API has changed in CiviCRM 2 Changes in CiviCRM 2 . Please review these changes before attempting to use the following examples. |
 | 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: v1 test cases * and *****v2 test cases. To run one of these test files, use the following URL (replacing GetCustomField in the example below with the name of the test file - omit the .php extension):
(For running v1 test cases)
http://(your server)/(your drupal root)/modules/civicrm/test-new/SimpleTest/OneTest.php?q=api/GetCustomField
(For running v2 test cases)
http://(your server)/(your drupal root)/modules/civicrm/test-new/SimpleTest/OneTest.php?q=api-v2/GetCustomField |
 | 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:
- civicrm.settings.php (remember where you put this during installation)
- $civicrm_root/CRM/Core/Config.php
- include specific php files within the api directory (Prior to 2.x version, you need to include $civicrm_root/api/crm.php for v1 APIs)
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:
$config =& CRM_Core_Config::singleton( );
Now you can enjoy making all the API calls you want! Example:
require_once("../../../default/civicrm.settings.php");
global $civicrm_root;
require_once($civicrm_root.'/CRM/Core/Config.php');
require_once "api/v2/Contribution.php";
$config =& CRM_Core_Config::singleton( );
$contribution = civicrm_contribution_get();
|
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).
<?php
$myGroup = 'Newsletter Subscribers';
$results = getGroupMembers($myGroup);
if ($results) {
echo '<h3>' . $myGroup . '</h3>';
foreach ($results[0] as $myContact) {
$string = 'ID: ' . $myContact[CRM:'contact_id'] . ' ' .
$myContact[CRM:'sort_name'] . ', ' . $myContact[CRM:'email'] . ', Phone: ' .
$myContact[CRM:'phone'];
echo $string . '<br />---<br />';
}
}
else {
echo 'No group found with that name.';
}
function getGroupMembers($group_title) {
if (!module_exists('civicrm')) return false;
civicrm_initialize( );
$groupGet = array('title' => $group_title)
$groups =& civicrm_groups_get( $groupGet );
$params = array('group' => array($groups[0]['id'] => 1)
'return.sort_name' => 1,
'return.email' => 1,
'return.phone' => 1
'sort' => array('sort_name' => 'ASC') );
$contacts =& civicrm_contact_search( $params );
if (!$contacts) return false;
return $contacts;
}
?>
Retrieve info for a contact with a given email address using civicrm_contact_search
<?php
if (module_exists('civicrm')) {
civicrm_initialize( );
$params = array ('email' => 'dave.green@example.org'
'return.first_name' => 1,
'return.last_name' => 1,
'return.email' => 1,
'return.phone' => 1,
'return.postal_code' => 1,
'return.state_province' =>1,
'return.country' => 1);
list($myContacts, $dontCare) = civicrm_contact_search( $params );
if ($myContacts) {
foreach ($myContacts as $myContact) {
$display = $myContact[CRM:'first_name'] . ' ' .
$myContact[CRM:'last_name'] . '<br />' .
$myContact[CRM:'email'] . '<br />' .
$myContact[CRM:'phone'] . '<br />' .
$myContact[CRM:'postal_code'] . ', ' .
$myContact[CRM:'state_province'] . ' ' .
$myContact[CRM:'country'] . '<br />---<br />';
echo $display;
}
} else {
echo 'No contact found with that email address.';
}
}
?>
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.
<?php
if (module_exists('civicrm')) {
civicrm_initialize( );
require_once 'api/v2/Event.php';
$params = array ('event_type_id' => 3,
'is_public' => 1);
$myEvents = civicrm_event_search( $params );
if ($myEvents) {
foreach ($myEvents as $event) {
$display = $event['title'] . '<br />Starts: ' .
$event['start_date'] . '<br />Ends: ' .
$event['end_date'] . '<br /><hr>';
echo $display;
}
} else {
echo 'No events found.';
}
}
?>
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). This also provides display for events with date ranges:
<?php
function civi_date_sorting($a,$b) {
if ($a['start_date'] > $b['start_date']) return -1;
if ($a['start_date'] < $b['start_date']) return 1;
return 0;
}
if (module_exists('civicrm')) {
civicrm_initialize(TRUE);
require_once 'api/v2/Event.php';
$params = array ('is_public' => 1, 'is_active' => 1);
$myEvents = civicrm_event_search( $params );
if ($myEvents) {
$count = 0;
usort($myEvents,'civi_date_sorting');
foreach ($myEvents as $event) {
$now = time( );
$endDate = CRM_Utils_Date::unixTime( $event['end_date'] );
if ( $now <= $endDate) {
$startdate = date('n/j',strtotime($event['start_date']));
$enddate = date('n/j',strtotime($event['end_date']));
if($startdate != $enddate){
$finaldate = $startdate." - ".$enddate;
}
else{
$finaldate = $startdate;
}
$eventid = $event['id'];
list($title_place, $title_desc) = split(":",$event['title'],2);
$display = '<ul><li class="event"><span class="time">'.$finaldate.'</span>';
$display .= l($title_place.' '.$title_desc, 'civicrm/event/info', array(), 'reset=1&id='.$event['id']).'</li></ul>';
echo $display;
$count++;
if ($count > 6) break;
} } if ($count = 0) {
echo 'No events are currently scheduled.';
}
}
else {
echo 'No events found.';
}
}
?>
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.
*
* Implementation of hook_settings().
*/
function hook_settings() {
if (module_exists('civicrm')) {
civicrm_initialize( );
require_once 'api/v2/Group.php';
$g = civicrm_groups_get( );
$groups = array(' ');
foreach ($g as $v) {
$groups[CRM:$v['id']] = $v['title'];
}
foreach (user_roles() as $rid => $role) {
if ($rid > 2) $form .= form_select($role.' Group',
'join_group_'.$rid, variable_get('join_group_'.$rid, 0), $groups);
}
}
return $form;
}
/*
* Implementation of hook_user().
*/
function hook_user($op, &$edit, &$user, $category = NULL) {
switch ($op) {
case 'insert':
$user->roles = array();
$edit[CRM:'roles'] = array_flip($edit[CRM:'roles']);
case 'update':
if (module_exists('civicrm')) {
civicrm_initialize( );
$params = array('contact_id' => crm_uf_get_match_id($user->uid));
require_once 'api/v2/Contact.php';
$contact = civicrm_contact_get($params);
if (!$newroles = $edit[CRM:'roles']) $newroles = array();
if (!$oldroles = $user->roles) $oldroles = array();
require_once 'api/v2/GroupContact.php';
foreach ($newroles as $key => $value) {
if (!array_key_exists($key, $oldroles)) {
if ($g = variable_get('join_group_'.$key, 0)) {
$params = array('id' => $g);
$group = civicrm_groups_get($params);
$gcParams = array( );
$gcParams['contact_id.1'] = $contact['contact_id'];
foreach( $groups as $gid => $dontcare) {
$gcParams['group_id.' . $gid] = $gid;
}
$gsParams['method'] = 'API';
$gsParams['status'] = 'added';
require_once 'api/v2/GroupContact.php';
civicrm_group_contact_add( $gcParams );
}
}
}
foreach ($oldroles as $key => $value) {
if (!array_key_exists($key, $newroles)) {
if ($g = variable_get('join_group_'.$key, 0)) {
$params = array('id' => $g);
$group = civicrm_groups_get($params);
$group = array_values( $group );
$gdParams = array( );
$gdParams['contact_id'] = $contact['contact_id'];
$gdParams['group_id.'1] = $group[0]['id'];
$gdParams['method'] = 'API';
$gdParams['status'] = 'removed';
civicrm_group_contact_remove( $gdParams );
}
}
}
}
break;
Check status of an email address entered on a custom subscription form.
This snippet was contributed by Josh On.
function check_email_status($e_mail){
global $user;
$status = "";
civicrm_initialize( );
/*-- IS THE EMAIL A DRUPAL USER? --*/
if ($error = user_validate_mail($e_mail)) {
$status .= $e_mail . "is not a valid email";
return 1; }
else if (db_num_rows($result = db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(mail) =
LOWER('%s')", $uid, $e_mail)) > 0) {
while ($my_user = db_fetch_object($result)) {
$status .= " email is in Drupal |";
$myuserid .= $my_user->uid;
$is_in_drupal = 1;
}
}
else if (user_deny('mail', $e_mail)) {
$status .= $e_mail . " has been denied access. |";
return 2; }
/*-- IS THE CURRENT USER LOGGED IN? --*/
if ($user->uid) {
$status .= "logged in |";
$is_logged_in = 1;
if ($user->uid == $myuserid){
$status .= " same user |";
$is_same_user = 1;
} else {
$status .= " different user |";
}
} else {
$status .= " anon user |";
}
/*-- DOES THE CIVICRM EMAIL EXIST --*/
$params = array ("email" => $e_mail
"return.email" => 1);
$myContact =& crm_get_contact( $params );
if (!$myContact['contact_id']){
$status .= " NO CIVICRM ID ";
} else {
$status .= "CIVICRM ID:".$myContact['contact_id'] ;
$is_in_civicrm = 1;
}
/*-- RETURN RESULTS --*/
/*
CASE 1: email invalid
CASE 2: email has been blocked
CASE 3: logged in | same email | email in civicrm
CASE 4: logged in | same email | email not in civicrm
CASE 5: logged in | diff email | email in civicrm | email in drupal
CASE 6: logged in | diff email | email in civicrm | email not in drupal
CASE 7: logged in | diff email | email not civicrm | email in drupal
CASE 8: logged in | diff email | email not in civicrm | email not in drupal
CASE 9: not logged in | email in civicrm | email in drupal
CASE 10: not logged in | email in civicrm | email not in drupal
CASE 11: not logged in | email not in civicrm | email in drupal
CASE 12: not logged in | email not in civicrm | email not in drupal
*/
if ($is_logged_in){
if($is_same_user){
if($is_in_civicrm){
return 3;
} else {
return 4;
}
} else {
if($is_in_civicrm){
if ($is_in_drupal){
return 5;
} else {
return 6;
}
} else {
if ($is_in_drupal){
return 7;
} else {
return 8;
}
}
}
} else {
if($is_in_civicrm){
if ($is_in_drupal){
return 9;
} else {
return 10;
}
} else {
if ($is_in_drupal){
return 11;
} else {
return 12;
}
}
}
}
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.
function tokenize_profile($pid, $prepend) {
return tokenize_profile_fields(get_profile_fields($pid), $prepend);
}
function get_profile_fields($pid) {
if (function_exists('civicrm_initialize')) {
civicrm_initialize( );
$profile = crm_uf_get_profile_fields($pid);
return $profile;
}
}
function tokenize_profile_fields($profile, $prepend, $delimiter = '%') {
$tokens = array();
if($prepend != '') {
$prepend .= '-';
}
foreach($profile as $key => $profile_item) {
$tokens[CRM:$key] = make_token('%', $prepend, $profile_item[CRM:'title']);
}
return $tokens;
}
function make_token($delimiter, $prepend, $text) {
return $delimiter . $prepend . str_replace (' ', '-', trim($text)) . $delimiter;
}
Here is some example code about how this might be used (taken from CiviContact, with appropriate name changes):
$member_tokens = _civicontact_tokenize_profile($memberprofile, 'member');
$target_tokens = _civicontact_tokenize_profile($targetprofile, 'target');
$member_token_string = implode(', ', $member_tokens);
$target_token_string = implode(', ', $target_tokens);
$help_text = t('<p>You may use the following tokens for members: %members</p><p>You may use the following tokens for targets: %targets</p>',
array('%members' => $member_token_string, '%targets' => $target_token_string));
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. 
function filter_user_by_profile($user_id, $profile_id) {
civicrm_initialize( );
$output = array();
CRM_Core_BAO_UFGroup::getValues($user_id, crm_uf_get_profile_fields($profile_id), $output);
$output[CRM:'id'] = $user_id;
return $output;
}
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.
function untokenize_profile($mapping, $text, $prepend = '', $delimiter = '%') {
if($prepend != '') {
$prepend .= '-';
}
foreach($mapping as $key => $value) {
$token = make_token('%', $prepend, $key);
$token = preg_quote($token); $text = preg_replace('/' . $token . '/', $value, $text);
}
return $text;
}
Here's some more sample code that ties steps 2 and 3 together.
$text = 'some text that includes the tokens..... '
$member_mapping = filter_user_by_profile($memberid, $memberpid);
$target_mapping = filter_user_by_profile($targetpid, $targetpid);
$text = untokenize_profile($member_mapping, $text, 'member');
$text = untokenize_profile($target_mapping, $text, 'target');
print $text;
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.
function et_group_form( $multi = false, $required = false, $default = NULL, $title = '', $description = '') {
if (function_exists('civicrm_initialize')) {
civicrm_initialize( );
$groups = CRM_Core_Permission_Drupal::group( );
if($default != NULL && !isset($groups[CRM:$default])) {
$grp_array = civicrm_groups_get(array('id' => $default));
$new_group = array_pop($grp_array);
$groups[CRM:$default] = $new_group['title'];
}
if($description == '') {
$description = t('Please select a group. To add more groups visit %link', array('%link' => l('CiviCRM >> Group >> Add', 'civicrm/group/add')));
}
if($title == '') {
$title = $multi ? t('Groups') : t('Group');
}
$form = array(
'#type' => 'select',
'#title' => $title,
'#default_value' => $default,
'#multiple' => $multi,
'#description' => $description,
'#required' => $required,
'#options' => $groups,
);
return $form;
}
}
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>)
function get_user_object($uid) {
civicrm_initialize(true);
$userID = crm_uf_get_match_id($uid);
$cg = array( 'contact_id' => $userID );
return civicrm_contact_get( $cg );
}
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.
<?php
$myGroup = 'Your Group Name'; $myPrecision = 2;
if (module_exists('civicrm')) {
civicrm_initialize(TRUE);
$params = array('title' => $myGroup);
$return_properties = array('member_count', 'id');
$groups =& crm_get_groups($params, $return_properties);
if ($groups) {
if ($groups[0]->member_count == 0) {
$group = array($groups[0]->id => 1);
$params = array('group' => $group);
$result =& crm_contact_search_count($params);
if ($result) {
$num = $result;
}
} else {
$num = $groups[0]->member_count;
}
if ($myPrecision > 0 && $num > 0) {
$multiplier = pow(10, $myPrecision);
$num = floor($num / $multiplier) * $multiplier;
}
print $num;
}
}
?>
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.
<?php
if (!module_exists('civicrm')) return false;
civicrm_initialize( );
$select = "
SELECT civicrm_contribution.contact_id,
SUM( civicrm_contribution.total_amount ) as total_amount
FROM civicrm_contribution
WHERE civicrm_contribution.receive_date >= '2005-04-20'
AND civicrm_contribution.receive_date <= '2006-10-20'
AND civicrm_contribution.contribution_type_id = 4
AND civicrm_contribution.cancel_date IS NULL
GROUP BY civicrm_contribution.contact_id ";
$query = $select;
$params = array( );
print $query . "\n\n";
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
while ( $dao->fetch( ) ) {
$cg = array( 'contact_id' => $dao->contact_id );
$contact = civicrm_contact_get( $cg );
echo "'" . $contact['sort_name'] . "',";
echo "'" . $contact['display_name'] . "',";
echo "'" . $dao->contact_id ."',";
echo "'" . $dao->total_amount . "'<br />\r\n";
}
?>
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.
<?php
if (!module_exists('civicrm')) return false;
civicrm_initialize( );
$select = "
SELECT civicrm_contribution.contact_id,
SUM( civicrm_contribution.total_amount ) as total_amount
FROM civicrm_contribution
WHERE civicrm_contribution.receive_date >= '2005-04-20'
AND civicrm_contribution.receive_date <= '2006-10-20'
AND civicrm_contribution.contribution_type_id = 4
AND civicrm_contribution.cancel_date IS NULL
GROUP BY civicrm_contribution.contact_id ";
$query = $select;
$params = array( );
print $query . "\n\n";
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
while ( $dao->fetch( ) ) {
$cg = array('contact_id' => $dao->contact_id);
$contact = civicrm_contact_get( $cg );
echo "'" . $contact['sort_name'] . "',";
echo "'" . $contact['display_name'] . "',";
echo "'" . $dao->contact_id ."',";
echo "'" . $dao->total_amount . "'<br />\r\n";
}
?>
Display a list of recent contributors
This displays a list of recent contributors.
<?php
civicrm_initialize( );
$params = array( 'return.id' => 1);
$contributions = civicrm_contribution_search( $params );
foreach ($contributions as $contribution_id) {
$contribGet = array( "contribution_id" => $contribution_id );
$contribution = civicrm_contribution_get( $contribGet );
$cg = array("contact_id" => $contribution['contact_id'])
$contact = civicrm_contact_get($cg);
$contributions_array[] = array("name" => $contact['display_name'], "date" => $contribution['receive_date']);
}
krsort($contributions_array);
foreach ($contributions_array as $acontribution){
print $acontribution[CRM:'name'] . "<br />";
}
}
?>
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.
/**
* looks up a civicrm product name
*/
function getProductFromId($id = NULL){
static $products;
civicrm_initialize( );
if(!($id)) { return; } if($products[CRM:$id]) {return $products[CRM:$id];}
$query = "SELECT name, description FROM civicrm_product WHERE id = %1";
$params = array(1 => array($id, "Integer"));
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
while ( $dao->fetch() ) {
$products[CRM:$id] = array("name" => $dao->name, "description" => $dao->description);
}
return $products[CRM:$id];
}
/**
* builds the fulfillment page
*/
function fulfillment_page(){
drupal_set_title("Premiums to fulfill");
civicrm_initialize( );
$premiums = array();
$query = "SELECT contribution_id, product_option, product_id FROM civicrm_contribution_product WHERE fulfilled_date IS NULL";
$params = array();
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
while ( $dao->fetch() ) {
$premiums[CRM:$dao->contribution_id] = array(
"contribution_id"=> $dao->contribution_id,
"option" => $dao->product_option,
"product" => getProductFromId($dao->product_id)
);
}
$contributions = array();
foreach($premiums as $premium_id => $apremium){
$contribGet = array( "contribution_id" => $premium_id );
$contributions[CRM:$premium_id] = civicrm_contribution_get($contribGet);
}
if($contributions){
foreach($contributions as $premium_id => $contribution){
$cg = array("contact_id" => $contribution->contact_id);
if($contribution->contribution_status_id == 1){
$contacts[CRM:$premium_id] = civicrm_contact_get($cg);
}
}
if($contacts){
foreach($contacts as $premium_id => $contact){
$row = array(
$contact['display_name'],
$premiums[CRM:$premium_id][CRM:'product'][CRM:'name'],
$premiums[CRM:$premium_id][CRM:'option'],
l("Fulfill", "civicrm/contact/view/contribution", null, "reset=1&id=" . $premium_id ."&cid=". $contact['contact_id'] ."&action=view&context=search&selectedChild=contribute")
);
$rows[] = $row;
}
}
}
$header= array(t('Name'), t('Premium'), t('Option'), t('Fulfill'));
if(!($rows)){ $rows[][] = t("No premimums need to be fulfilled"); }
$output = theme("table", $header, $rows);
$output .= "Please note, this only lists premiums whose status is <em>completed</em>";
return $output;
}
Display list of upcoming birthdays
This display a list of the birthdays in the next 7 days, with a link to the contact pages.
if (!module_exists('civicrm')) return false;
civicrm_initialize( );
$select = "SELECT contact_id, birth_date, CONCAT(((RIGHT(birth_date,5) < RIGHT(CURRENT_DATE,5)) + YEAR(CURRENT_DATE)), RIGHT(birth_date,6)) AS bday, concat(concat(month(birth_date), '/'), day(birth_date)) as displaydate, (TO_DAYS(CONCAT(((RIGHT(birth_date,5) < RIGHT(CURRENT_DATE,5)) + YEAR(CURRENT_DATE)), RIGHT(birth_date,6))) - TO_DAYS(CURRENT_DATE)) AS toBday FROM civicrm_individual WHERE (TO_DAYS(CONCAT(((RIGHT(birth_date,5) < RIGHT(CURRENT_DATE,5)) + YEAR(CURRENT_DATE)), RIGHT(birth_date,6))) - TO_DAYS(CURRENT_DATE) < 7) ORDER BY bday, RIGHT(birth_date,5);";
$query = $select;
$params = array( );
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
echo "<div class=\"item-list\"><ul>\n";
while ( $dao->fetch( ) ) {
$cg = array('contact_id' => $dao->contact_id)
$contact = civicrm_contact_get($cg);
echo "<li><a href=\"/civicrm/contact/view?reset=1&cid=" . $dao->contact_id . "\">" . $contact['display_name'] . "</a>, " . $dao->displaydate;
echo "</li>\n";
}
echo "</ul></div>\n";
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!
<div id="eventspage" class="all2008">
<a name="top"></a> <?php
function cmp_date2($a,$b) {
if ($a['start_date'] > $b['start_date']) return 1;
if ($a['start_date'] < $b['start_date']) return -1;
return 0;
}
if (module_exists('civicrm')) {
civicrm_initialize(TRUE);
require_once 'api/v2/Event.php';
$params = array ('is_public' => 1, 'is_active' => 1);
$myEvents = civicrm_event_search( $params );
if ($myEvents) {
$count = 0;
$last = '';
usort($myEvents,'cmp_date2');
print "<ul>\n";
for ($i=0;$i < sizeof($myEvents); $i++) {
$event = $myEvents[$i];
$now = date('Y-m-d H:i:s');
if ($now > $event['start_date']) continue;
list($title_place, $title_desc) = split(":",$event['title'],2);
print "<li><a href=\"#event$i\">$title_place</a></li> \n";
}
print "</ul>\n";
for ($j=0;$j < sizeof($myEvents); $j++) {
$event = $myEvents[$j];
$now = date('Y-m-d H:i:s');
if ($now > $event['start_date']) continue;
$startdate = date('D M j Y',strtotime($event['start_date']));
$enddate = date('D M j Y',strtotime($event['end_date']));
$starttime = date('g:i A',strtotime($event['start_date']));
$eventid = $event['id'];
list($title_place, $title_desc) = split(":",$event['title'],2);
$display = l($title_place.' '.$title_desc, 'civicrm/event/info', array(), 'reset=1&id='.$event['id']);
echo '<div>';
echo '<a name="event' . $j . '"></a>';
echo '<h3>'.$display.'</h3>';
$discr = $event['description'];
echo '<p>'.$discr.'</p>';
if ($last != $startdate) {
$start_date = '<b> WHEN: </b>'.$startdate;
}
print $start_date.'<br/>';
print '<b>TIME: </b>'.$starttime ;
echo '<br>';
require_once 'CRM/Core/DAO/LocBlock.php';
$addId = CRM_Core_DAO::getfieldvalue('CRM_Core_DAO_LocBlock',$event['loc_block_id'],'address_id');
if($addId){
$query
= "SELECT street_address , supplemental_address_1 , city ,
sp.abbreviation ,postal_code, cc.name FROM civicrm_address LEFT JOIN
civicrm_state_province sp ON (civicrm_address.state_province_id =sp.id
)LEFT JOIN civicrm_country cc ON (civicrm_address.country_id =cc.id )
WHERE civicrm_address.id=$addId";
$params = array();
$dao =& CRM_Core_DAO::executeQuery( $query, $params );
$dao->fetch( );
$location = '<b>WHERE: </b>' ;
if($dao->street_address){
$location.= $dao->street_address.'<br />';}
if($dao->supplemental_address_1){
$location.= $dao->supplemental_address_1.'<br />';}
if($dao->city){
$location.= $dao->city.','.$dao->abbreviation.' '.$dao->postal_code.'<br />';}
print $location;
}
require_once 'CRM/Event/DAO/EventPage.php';
$pageGroup= new CRM_Event_DAO_EventPage($eventid);
$pageID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_EventPage', $eventid, 'id', 'event_id');
require_once 'CRM/Core/DAO/OptionGroup.php';
$optionGroupDAO = new CRM_Core_DAO_OptionGroup();
$optionGroupDAO->name = 'civicrm_event_page.amount.'.$pageID;
$ss = array();
$i = 0;
if ($optionGroupDAO->find(true) ) {
$optionGroupId = $optionGroupDAO->id;
require_once 'CRM/Core/DAO/OptionValue.php';
$optionValueDAO = new CRM_Core_DAO_OptionValue();
$optionValueDAO->option_group_id = $optionGroupDAO->id;
$optionValueDAO->find();
while ( $optionValueDAO->fetch( ) ) {
$ss['optionLable'][$i] = $optionValueDAO->label;
$ss['optionValue'][$i] = $optionValueDAO->value;
$i++;
}
}
require_once 'CRM/Core/BAO/PriceSet.php';
$priceSetId = CRM_Core_BAO_PriceSet::getFor( 'civicrm_event_page', $eventid );
if($ss['optionValue'] && !$priceSetId){
print '<b>COST: </b>'.'$'.$ss['optionValue'][0].' per person' ;
}
if ($event['is_online_registration'] ) {
echo "<p class=\"regbutton\"><a href=\"http:}
echo '<p class="totop"><a href="http: class="totop">top</a></p>';
echo '</div>';
$count++;
$last = $startdate;
}
if ($count > 0) {
} else {
echo 'No events found.';
}
} else {
echo 'No events found.';
}
}
?></div>
<p> </p>
|
|
Are the instructions under "Getting Started with Standalone Scripts" still accurate? Isn't it simply enough to call civicrm_initialize() ?
The examples do not seem to work at all..
first of all $civicrm_root.'/api/crm.php does not exist (at least not in my installation, there are some other php files in that api directory though...)
Also the example page does not exist: modules/civicrm/test/OneTest.php?q=GetCustomField
And if I take the first block example: the function getGroupMembers is not defined anywhere in the CiviCRM files.
Note that the API changed a lot in CiviCRM 2. See this doc
Changes in CiviCRM 2