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

CiviCRM hook specification

Skip to end of metadata
Go to start of metadata

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

 All versions (click to expand)

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.

Goals and Background

This documents how to extend CiviCRM to meet your needs. We are extending CiviCRM in a very similar manner to Drupal, primarily because based on our experience with Drupal's extension architecture, we think it is clean and non-intrusive, yet incredibly powerful. For a simple example module check civitest module

See Drupal hook documentation for a description of how hooks are implemented.

See the section on Joomla within this article for a description of how to implement hooks in Joomla.

See CRM/Utils/Hook.php for CiviCRM for the source code that invokes these hooks.

Procedures for implementing hooks (for Drupal)

All your hook implementations should be collected within one or more modules, so to begin create a module:

  • Select a short name for your module (e.g. highschool).
  • Create, e.g.,  highschool.info and .module files, and store them in /sites/all/modules/myCiviModule/ (you can rename the directory"myCiviModule" to something more appropriate).  Once you enable the module(s) in Drupal's Administer panel, Drupal will automagically load it and civiCRM will call any hooks that have the proper suffix (e.g. xxxxxxx_civicrm_postProcess).
  • For a well-commented, working example of using hooks to store a last modified date when a user clicks the "Save" button on a profile form, see the hook_civicrm_postProcess hook documentation below. You can also find examples in your CiviCRM install in civicrm\drupal\civitest.module.sample
  • Here is an example of a .info file:

Procedures for implementing hooks (for Joomla)

  • Create a single file called civicrmHooks.php.  This file will hold all your hook implementations.
  • Upload the file civicrmHooks.php to a new directory called /my_custom_civicrm_code/ or something similar of your choosing.   This new directory should be located outside of the area where CiviCRM resides. This is so when CiviCRM is upgraded to a new version, your custom file is not touched.
  • Go into the area  "CiviCRM Administer ... Global Settings ... Directories."   Change the value of Custom PHP Path Directory to the absolute path to the new directory. Such as /home/account/my_custom_civiCRM_code/
  • Write the implementations for all your hooks in the file civicrmHooks.php.  All the functions need to start with the name joomla_  instead of hook.   If the hook you want to implement is called hook_civicrm_tokens, then your function should be named joomla_civicrm_tokens.
  • An example of what goes in the civicrmHooks.php file is below:

Note on setting and getting custom field values in hooks

For setting and getting custom field values in hooks, you need to know the field ID of the custom field(s) you want to work with. The easiest place to find these IDs is in the civicrm_custom_field table in the database. You'll then access these fields as "custom_ID". So if you have a field holding a custom value whose ID in the civicrm_custom_field table is 34, you'll use "custom_34" to access it.

Once you have the ID(s), you'll want to use the setValues and getValues functions in the CRM/Core/BAO/CustomValueTable.php file. Here are a couple of examples of their use:

Setting values (on a Contribution object's custom fields):

Getting values (from a Contribution's associated Contact object):

hook_civicrm_pre

Description

This hook is called before a db write on some core objects. This hook does not allow the abort of the operation, use a form hook instead.

We suspect the pre hook will be useful for developers building more complex applications and need to perform operations before CiviCRM takes action. This is very applicable when you need to maintain foreign key constraints etc (when deleting an object, the child objects have to be deleted first). Another good use for the pre hook is to see what is changing between the old and new data.

Definition
Parameters
  • $op - operation being performed with CiviCRM object. Can have the following values:
    • 'view' : The CiviCRM object is going to be displayed
    • 'create' : The CiviCRM object is created (or contacts are being added to a group)
    • 'edit' : The CiviCRM object is edited
    • 'delete' : The CiviCRM object is being deleted (or contacts are being removed from a group)
  • $objectName - can have the following values:
    • 'Individual'
    • 'Household'
    • 'Organization'
    • 'Group'
    • 'GroupContact'
    • 'Relationship'
    • 'Contribution'
    • 'Profile' (while this is not really an object, people have expressed an interest to perform an action when a profile is created/edited)
    • 'Membership'
    • 'Event'
    • 'Participant'
    • 'UFMatch' (when an object is linked to a CMS user record, at the request of GordonH. A UFMatch object is passed for both the pre and post hooks)
  • $objectId the object id if available
  • &$objectRef the parameters used for object creation / editing
Returns
  • None
Example

hook_civicrm_post

Description

This hook is called after a db write on some core objects.

pre and post hooks are useful for developers building more complex applications and need to perform operations before CiviCRM takes action. This is very applicable when you need to maintain foreign key constraints etc (when deleting an object, the child objects have to be deleted first).

Definition
Parameters
  • $op - operation being performed with CiviCRM object. Can have the following values:
    • 'view' : The CiviCRM object is going to be displayed
    • 'create' : The CiviCRM object is created (or contacts are being added to a group)
    • 'edit' : The CiviCRM object is edited
    • 'delete' : The CiviCRM object is being deleted (or contacts are being removed from a group)
  • $objectName - can have the following values:
    • 'Individual'
    • 'Household'
    • 'Organization'
    • 'Group'
    • 'GroupContact'
    • 'Relationship'
    • 'Activity'
    • 'Contribution'
    • 'Profile' (while this is not really an object, people have expressed an interest to perform an action when a profile is created/edited)
    • 'Membership'
    • 'Participant'
    • 'UFMatch' (when an object is linked to a CMS user record, at the request of GordonH. A UFMatch object is passed for both the pre and post hooks)
    • 'Event'
    • 'EntityTag'
  • $objectId - the unique identifier for the object. tagID in case of EntityYag
  • $objectRef - the reference to the object if available. For case of EntityTag it is an array of (entityTable, entityIDs)
Returns
  • None
Example

Here is a simple example that will send you an email whenever an INDIVIDUAL Contact is either Added, Updated or Deleted:

Create a new folder called example_sendEmailOnIndividual in this directory /drupal_install_dir/sites/all/modules/civicrm/drupal/modules/ and then put the following two files in that directory (change the email addresses to yours).

FILE #1 /drupal_install_dir/sites/all/modules/civicrm/drupal/modules/example_sendEmailOnIndividual/example_sendEmailOnIndividual.info
FILE #2 /drupal_install_dir/sites/all/modules/civicrm/drupal/modules/example_sendEmailOnIndividual/example_sendEmailOnIndividual.module

Once the files are in the directory, you need to login to Drupal admin, go to Modules and enable our new module and click Save. Now go and edit a contact and you should get an email!

Description

These hooks are used to inject UI into CiviCRM pages such as the Contact Summary page.

Note: remember to use the string & url processing functions of your host framework ( url() and t() for Drupal ).

Definition
Parameters
  • $op = 'view.contact.activity' OR 'view.contact.userDashBoard'
  • $objectName = 'Contact'
  • $objectId -the CiviCRM internal ID of the object (a contact ID.).
  • $links - (optional) the links array to modify in-place
Returns
  • an array of arrays, each element is a tuple consisting of url, title (and depending on the operation some other parameters)
Example

hook_civicrm_validate

Description

Validation of forms

Definition
Parameters
  • $formName - Name of the form being validated, you will typically switch off this value.
  • $fields - Array of name value pairs for all 'POST'ed form values
  • $files - Array of file properties as sent by PHP POST protocol
  • $form - Reference to the civicrm form object. This is useful if you want to retrieve any values that we've constructed in the form
Returns

true if form validates successfully, otherwise array with error message strings

Example

Beginning in CiviCRM 3.2, from within this hook, you can also manipulate validation errors set by CiviCRM. For example, to unset a validation error triggered by CiviCRM:

hook_civicrm_buildForm

Description

This hook is invoked when building a CiviCRM form. This hook should also
be used to set the default values of a form element

Definition
Parameters
  • string $formName - the name of the form
  • object $form - reference to the form object
    Returns
Example

hook_civicrm_postProcess

Description

This hook is invoked when a CiviCRM form is submitted. If the module has injected
any form elements, this hook should save the values in the database.

Definition
Parameters
  • string $formName - the name of the form
  • object $form - reference to the form object
Returns
  • null - the return value is ignored
Example

hook_civicrm_custom

Description

This hook is called AFTER the db write on a custom table

Definition
Parameters
  • string $op - the type of operation being performed
  • string $groupID - the custom group ID
  • object $entityID - the entityID of the row in the custom table
  • array $params - the parameters that were sent into the calling function
Returns
  • null - the return value is ignored
Example

hook_civicrm_aclWhereClause

Description

This hook is called when composing the ACL where clause to restrict visibility of contacts to the logged in user.

NB: This function will not be called at all if the logged in user has access to the "edit all contacts" permission.

Definition
Parameters
  • $type - type of permission needed
  • array $tables - (reference ) add the tables that are needed for the select clause
  • array $whereTables - (reference ) add the tables that are needed for the where clause
  • int $contactID - the contactID for whom the check is made
  • string $where - the currrent where clause
Returns
  • null - the return value is ignored
Example

hook_civicrm_aclGroup

Description

This hook is called when composing the ACL to restrict access to civicrm entities (civicrm groups, profiles and events). NOTE: In order to use this hook you must uncheck "View All Contacts" AND "Edit All Contacts" in Drupal Permissions for the user role you want to limit. You can then go into CiviCRM and grant permission to Edit or View "All Contacts" or "Certain Groups". See the Forum Topic at: http://forum.civicrm.org/index.php/topic,14595.0.html for more information.

Definition
Parameters
  • $type the type of permission needed
  • $contactID the contactID for whom the check is made
  • $tableName the tableName which is being permissioned
  • $allGroups the set of all the objects for the above table
  • $currentGroups the set of objects that are currently permissioned for this contact . This array will be modified by the hook
Returns
  • null - the return value is ignored
Example

Check HRD Module

hook_civicrm_dashboard

Description

This hook is called when rendering the dashboard page. This hook can be used to add content to the dashboard page.

Definition
Parameters
  • $contactID the contactID for whom the dashboard is being generated
  • $contentPlacement (output parameter) where should the hook content be displayed relative to the activity list. One of CRM_Utils_Hook::DASHBOARD_BELOW, CRM_Utils_Hook::DASHBOARD_ABOVE, CRM_Utils_Hook::DASHBOARD_REPLACE. Default is to add content BELOW the standard dashboard Activities listing. DASHBOARD_REPLACE replaces the standard Activities listing with the provided content.
Returns
  • the HTML to include in the dashboard
Example

Also check Civitest Sample Module

hook_civicrm_xmlMenu

Description

This hook is called when building CiviCRM's menu structure. You will need to visit <your_site>/civicrm/menu/rebuild&reset=1 to pick up your additions.

Definition
Parameters
  • $files the array for files used to build the menu. You can append or delete entries from this file. You can also override menu items defined by CiviCRM Core.
Returns
  • null

Example

Here's how you can override an existing menu item. First create an XML file like this, and place it in the same folder as your hook implementation:

<?xml version="1.0" encoding="iso-8859-1" ?>
<menu>
  <item>
     <path>civicrm/ajax/contactlist</path>
     <page_callback>CRM_Contact_Page_AJAX::getContactList</page_callback>
     <access_arguments>access CiviCRM AJAX contactlist</access_arguments>
  </item>
</menu>
Drupal developers can define 'my custom permission' using hook_perm . Then create a hook implementation like this:

hook_civicrm_alterPaymentProcessorParams

Description

This hook is called during the processing of a contribution after the payment processor has control, but just before the CiviCRM processor specific code starts a transaction with the back-end payments server (e.g., PayPal, Authorized.net, or Moneris). It allows you to modify the parameters passed to the back end so that you can pass custom parameters, or use features of your back-end that CiviCRM does not "know" about.

Definition
Parameters
  • $paymentObj - instance of payment class of the payment processor invoked
  • $rawParams - the associative array passed by CiviCRM to the processor
  • $cookedParams - the associative array of parameters as translated into the processor's API.
Returns
Example

hook_civicrm_pageRun

Description

This hook is called before a CiviCRM page is rendered

Definition
Parameters
  • $page the page being rendered
Returns
  • null

hook_civicrm_copy

Description

This hook is called after a CiviCRM object (Event, ContributionPage, Profile) has been copied

Definition
Parameters
  • $objectName - the name of the object that is being copied (Event, ContributionPage, UFGroup)
  • $object - reference to the copied object
Returns
  • null

hook_civicrm_tokens

Description

This hook is called to get all the tokens that can be used

Definition
Parameters
  • $tokens: reference to the associative array of tokens that are available to be used in mailings and other contexts.
Returns
  • null

hook_civicrm_tokenValues

Description

This hook is called to get all the values for the tokens registered

Definition
Parameters
  • $details - array of contactID details
  • $contactIDs - either a single contactID or an array of contactIDs that the system needs values for.
Returns
  • null

hook_civicrm_customFieldOptions

Description

This hook is called when CiviCRM needs to edit/display a custom field with options (select, radio, checkbox, adv multiselect)

Definition
Parameters
  • $fieldID - the custom field ID
  • $options - the current set of options for that custom field. You can add/remove existing options. Important: This array may contain meta-data about the field that is needed elsewhere, so it is important to be careful to not overwrite the array. Only add/edit/remove the specific field options you intend to affect.
  • $detailedFormat - if true, the options are in an ID => array ( 'id' => ID, 'label' => label, 'value' => value ) format
Returns
  • null
Example

This syntax may be more convenient if you are a managing differing sets of options for different fields:

hook_civicrm_searchTasks

Description

This hook is called to display the list of actions allowed after doing a contact search. This allows the module developer to inject additional actions or to remove existing actions.

Definition
Parameters
  • $objectType - the object for this search (currently only Contact, in later versions we will add membership / contribution / participants etc)
  • $tasks - the current set of tasks for that custom field. You can add/remove existing tasks. Each task needs to have a title and a class.
Returns
  • null
Example

hook_civicrm_buildAmount

Description

This hook is called when building the amount structure for a Contribution or Event Page. It allows you to modify the set of radio buttons representing amounts for contribution levels and event registration fees.

Definition
Parameters
  • $pageType - is this a 'contribution' or 'event'
  • $form - reference to the form object
  • $amount - the amount structure to be displayed
Returns
  • null
Example

hook_civicrm_tabs

Description

This hook is called when composing the tabs to display when viewing a contact

Definition
Parameters
  • $tabs - the array of tabs that will be displayed
  • $contactID - the contactID for whom the view is being rendered
Returns
  • null - the return value is ignored
Example

hook_civicrm_mailingGroups

Description

This hook is called when composing a mailing. You can include / exclude other groups as needed.

Definition
Parameters
  • $form - the form object for which groups / mailings being displayed
  • $groups - the list of groups being included / excluded
  • $mailings - the list of mailings being included / excluded
Returns
  • null - the return value is ignored
Example

hook_civicrm_shortcuts

Description

This hook is obsoleted in CiviCRM v3.2.4 in favor of hook_civicrm_links ( For more details check hook_civicrm_links documentation )

hook_civicrm_summary

Description

This hook is called when contact summary is rendered and you can add on top, below or replace summary with your own html content.

Definition
Parameters
  • $contactID the contactID for whom the contact summary is being generated
  • $contentPlacement (output parameter) where should the hook content be displayed relative to the exiting content. One of CRM_Utils_Hook::SUMMARY_BELOW, CRM_Utils_Hook::SUMMARY_ABOVE, CRM_Utils_Hook::SUMMARY_REPLACE. Default is to add content BELOW default contact summary content.
Example

hook_civicrm_contactListQuery

Description

Use this hook to populate the list of contacts returned by Contact Reference custom fields. By default, Contact Reference fields will search on and return all CiviCRM contacts. If you want to limit the contacts returned to a specific group, or some other criteria - you can override that behavior by providing a SQL query that returns some subset of your contacts. The hook is called when the query is executed to get the list of contacts to display.

Definition
Parameters
  • $query - the query that will be executed (input and output parameter); It's important to realize that the ACL clause is built prior to this hook being fired, so your query will ignore any ACL rules that may be defined. Your query must return two columns:
    • the contact 'data' to display in the autocomplete dropdown (usually contact.sort_name - aliased as 'data')
    • the contact IDs
  • $name - the name string to execute the query against (this is the value being typed in by the user)
  • $context - the context in which this ajax call is being made (for example: 'customfield', 'caseview')

    To find the context for a given contactListQuery widget, use firebug console and type in a few letters. You'll see a GET command that looks like this (and includes the context= parameter):http://drupal.demo.civicrm.org/civicrm/ajax/contactlist?context=caseview&s=ada&limit=10&timestamp=1273015964778

  • $id - the id of the object for which the call is being made. For custom fields, it will be the custom field id
Example

This example limits contacts in my contact reference field lookup (custom field id=4) to a specific group (group id=5)

hook_civicrm_membershipTypeValues

Description

This hook is called when composing the array of membershipTypes and their cost during a membership registration (new or renewal). Note the hook is called on initial page load and also reloaded after submit (PRG pattern). You can use it to alter the membership types when first loaded, or after submission (for example if you want to gather data in the form and use it to alter the fees).

Definition
Parameters
  • $form the form object that is presenting the page
  • $membershipTypeValues the array of membership types and their amount
Examples

Give a 50% discount to some memberships in the sample data

Modify specific fee values

hook_civicrm_alterMailParams

Description

This hook is called when an email is about to be sent by CiviCRM.

Definition
Parameters
  • $params the mailing params
Details
  • $params array fields include: groupName, from, toName, toEmail, subject, cc, bcc, text, html, returnPath, replyTo, attachments (array)
  • If you want to abort the mail from being sent, set the boolean abortMailSend to true in the params array

hook_civicrm_caseSummary

Description

This hook is called when the manage case screen is displayed. It allows the injection of label/value pairs which are rendered inside divs underneath the existing summary table.

Definition
Parameters
  • string $caseID - the case ID
Returns
  • array - an array where the key is a custom id that can be used for CSS styling the div and the value is an array with 'label' and 'value' elements.
Example

hook_civicrm_config

Description

This hook is called soon after the CRM_Core_Config object has ben initialized. You can use this hook to modify the config object and hence behavior of CiviCRM dynamically.

Definition
Parameters
  • $config the config object
Example

hook_civicrm_navigationMenu

Description

This hook is called after the menus are rebuild. You can use this hook to add new menu, add children to new menu and get the list of menu items for any parent.

Definition
Parameters
  • $params the navigation menu array

Attributes of the menu :

    1. label : Navigation Title

    2. Name : Internal Name

    3. url : url in case of custom navigation link

    4. permission : comma separated Permissions for menu item

    5. operator : Permission Operator ( AND/OR)

    6. seperator : If separator needs to be added after this menu item.

    7. parentID : Parent navigation item, used for grouping

    8. navID : ID of the menu

    9. active : is active ?

Example

hook_civicrm_merge

Description

This hook allows modification of the data used to perform merging of duplicates. This can be useful if your custom module has added its own tables related to CiviCRM contacts.

Availability

This hook was first available in CiviCRM 3.2.3.

Definition
Parameters
  • $type the type of data being passed (cidRefs|eidRefs|relTables|sqls)
  • $data the data, which depends on the value of $type (see Details)
  • $mainId contact_id of the contact that survives the merge (only when $type == 'sqls')
  • $otherId contact_id of the contact that will be absorbed and deleted (only when $type == 'sqls')
  • $tables when $type is "sqls", an array of tables as it may have been handed to the calling function
Details

The contents of $data will vary based on the $type of data being passed:

  • 'relTables':
    • an array of tables used for asking user which elements to merge, as used at civicrm/contact/merge; each table in the array has this format:
  • 'sqls':
    • a one-dimensional array of SQL statements to be run in the final merge operation;
    • These SQL statements are run within a single transaction.
  • 'cidRefs':
    • an array of tables and their fields referencing civicrm_contact.contact_id explicitely;
    • each table in the array has this format:
  • 'eidRefs':
    • an array of tables and their fields referencing civicrm_contact.contact_id with entity_id;
    • each table in the array has this format:
Example

hook_civicrm_export

Description

This hook allows to manipulate or change the output of CSV during export.

Availability

This hook was first available in CiviCRM 3.2.4

Definition
Parameters
  • @param string $exportTempTable - name of the temporary export table used during export
  • @param array $headerRows - header rows for output
  • @param array $sqlColumns - SQL columns
  • @param int $exportMode - export mode ( contact, contribution, etc...)
Details
Example
Labels:

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.