|
Table of Contents
Goals and BackgroundThis 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:
Procedures for implementing hooks (for Joomla)Plugins in the civicrm groups should be used to access hooks in Joomla. Information on Joomla plugin development can be found at http://docs.joomla.org/Plugin. Joomla plugins implement the observer design pattern. Hook plugins should be placed in the civicrm plugin group in a subfolder with the same name as the plugin.. Once created plugins may be packaged and installed with the Joomla installer or the files can be placed in the appropriate folder and installed with the discover method. A simple example is given below. It consists of two file tabs.php and tabs.xml along with the blank index.html file which is considered good Joomla coding practice. Tabs.php: Tabs.xml You can make plugins that include multiple hooks or you can make separate plugins. What is appropriate will depend on the application. 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): Note that custom field values may not always be available when you might expect. For instance, you can't retrieve custom field values in the 'create' operation in the _pre and _post hooks, because the custom field values haven't been stored yet. However, you can retrieve values in the 'edit' operation. Form related hookshook_civicrm_validateDescriptionValidation of forms. This hook will be removed in v4.3. Please us hook_civicrm_validateForm in v4.2 DefinitionParameters
Returnstrue if form validates successfully, otherwise array with input field names as keys and error message strings as values ExampleBeginning 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_validateForm (v4.2 and above)DescriptionValidation of forms. This hook was introduced in v4.2 DefinitionParameters
Returnstrue if form validates successfully, otherwise array with input field names as keys and error message strings as values ExampleBeginning 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_buildFormDescriptionThis hook is invoked when building a CiviCRM form. This hook should also be used to set the default values of a form element DefinitionParameters
ReturnsExample
hook_civicrm_alterContentDescriptionThis hook is invoked after all the content of a CiviCRM form or page is generated. It allows for direct manipulation of the generated content. DefinitionParameters
ReturnsExample
hook_civicrm_postProcessDescriptionThis hook is invoked when a CiviCRM form is submitted. If the module has injected This hook is not called when using the API, only when using the regular forms. If you want to have an action that is triggered no matter if it's a form or an API, use the pre and post hooks instead. DefinitionParameters
Returns
ExampleDatabase related hookshook_civicrm_preDescriptionThis 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. DefinitionParameters
**
Returns
Examplehook_civicrm_postDescriptionThis 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). DefinitionParameters
Returns
ExampleHere 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! hook_civicrm_customDescriptionThis hook is called AFTER the db write on a custom table DefinitionParameters
Returns
Examplehook_civicrm_copyDescriptionThis hook is called after a CiviCRM object (Event, ContributionPage, Profile) has been copied DefinitionParameters
Returns
Permission related hookshook_civicrm_aclWhereClauseDescriptionThis 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. DefinitionParameters
Returns
Examplehook_civicrm_aclGroupDescriptionThis 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. DefinitionParameters
Returns
ExampleCheck HRD Module GUI related hookshook_civicrm_linksDescriptionThese 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 ). DefinitionParameters
Returns
Examplehook_civicrm_dashboardDescriptionThis hook is called when rendering the dashboard page. This hook can be used to add content to the dashboard page. DefinitionParameters
Returns
ExampleAlso check Civitest Sample Module hook_civicrm_xmlMenuDescriptionThis hook is called when building CiviCRM's menu structure, which is used to render urls in CiviCRM. This hook should be used when you want to register your custom module url's in CiviCRM. You will need to visit <your_site>/civicrm/menu/rebuild?reset=1 to pick up your additions. Note: If you just want to register url in top Navigation, you should use hook_civicrm_navigationMenu DefinitionParameters
Returns
ExampleHere'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" ?> hook_civicrm_navigationMenuDescriptionThis 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. DefinitionParameters
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 ? Examplehook_civicrm_pageRunDescriptionThis hook is called before a CiviCRM page is rendered. Note that this does not execute on every CiviCRM page in the general sense. CiviCRM's pages are classified as either 'Forms' or 'Pages', and this only runs on pages classified as 'Pages'. If you are not sure if a particular page is a Page, test it by adding some temporary debug code to /CRM/Utils/Hook.php DefinitionParameters
Returns
hook_civicrm_customFieldOptionsDescriptionThis hook is called when CiviCRM needs to edit/display a custom field with options (select, radio, checkbox, adv multiselect) DefinitionParameters
Returns
ExampleThis syntax may be more convenient if you are a managing differing sets of options for different fields: hook_civicrm_summaryDescriptionThis hook is called when contact summary is rendered and you can add on top, below or replace summary with your own html content. DefinitionParameters
Examplehook_civicrm_summaryActionsDescriptionThis hook allows User to customize context menu Actions on Contact Summary Page. DefinitionParameters
Examplehook_civicrm_searchTasksDescriptionThis hook is called to display the list of actions allowed after doing a search. This allows the module developer to inject additional actions or to remove existing actions. DefinitionParameters
Returns
Examplehook_civicrm_searchColumnsDescriptionThis hook is called after a search is done. This allows the developer to modify the headers and/or the values that are displayed as part of this search. The BIGGEST drawback with this hook is that you may need to modify the result template to include your fields. The result files are CRM/{Contact,Contribute,Member,Event…}/Form/Selector.tpl. However, if you use the same number of columns, you can overwrite the existing columns with the values that you want displayed. This is a HACK, but avoids template modification. DefinitionParameters
Returns
Examplehook_civicrm_buildAmountDescriptionThis 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. DefinitionParameters
Returns
Examplehook_civicrm_tabsDescriptionThis hook is called when composing the tabs to display when viewing a contact DefinitionParameters
Returns
Examplehook_civicrm_alterMailingLabelParamsDescriptionThis hook is called to alter the parameters used to generate mailing labels. To be added in CiviCRM 4.1 or later. DefinitionParameters
@param array $args an array of the args for the tcpdf MultiCell api call with the variable names below converted into string keys
(ie $w become 'w' as the first key for $args).
If ishtml is set true, then a subset of the args will be passed to the tcdpdf writeHTMLCell api call instead.
float $w Width of cells. If 0, they extend up to the right margin of the page.
float $h Cell minimum height. The cell extends automatically if needed.
string $txt String to print
mixed $border Indicates if borders must be drawn around the cell block. The value can
be either
a number:
0: no border (default)
1: frame or
a string containing some or all of the following characters (in any order):
L: left
T: top
R: right
B: bottom
string $align Allows to center or align the text. Possible values are:
L or empty string: left align
C: center
R: right align
J: justification (default value when $ishtml=false)
int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
int $ln Indicates where the current position should go after the call. Possible values are:
0: to the right
1: to the beginning of the next line DEFAULT
2: below
float $x x position in user units
float $y y position in user units
boolean $reseth if true reset the last cell height (default true).
int $stretch stretch carachter mode:
0 = disabled
1 = horizontal scaling only if necessary
2 = forced horizontal scaling
3 = character spacing only if necessary
4 = forced character spacing
boolean $ishtml set to true if $txt is HTML content (default = false).
boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
float $maxh maximum height. It should be >= $h and less then remaining space to the bottom of the page,
or 0 for disable this feature. This feature works only when $ishtml=false.
NB: not all html tags are supported, not all style parameters are supported, and improperly constructed html tends to lead to errors and crashes. Returns
Examplehook_civicrm_alterPaymentProcessorParamsDescriptionThis 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. DefinitionParameters
ReturnsExamplehook_civicrm_tokensDescriptionThis hook is called to allow custom tokens to be defined. Their values will need to be supplied by hook_civicrm_tokenValues. Definition
|
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×tamp=1273015964778 |
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_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
hook_civicrm_emailProcessor
Description
This hook is called AFTER EACH email has been processed by the script bin/EmailProcessor.php
Definition
Parameters
- @param string $type type of mail processed: 'activity' OR 'mailing'
- @param array &$params the params that were sent to the CiviCRM API function
- @param object $mail the mail object which is an ezcMail class
- @param array &$result the result returned by the api call
- @param string $action (optional ) the requested action to be performed if the types was 'mailing'
Returns
- null
Availability
This hook was first available in CiviCRM 3.4.0
hook_civicrm_import
Description
This hook is called after contacts have been imported into the system, and before the temp import table has been destroyed. It can be used to take custom action on the imported records or handle special columns in the import file. It currently is only applicable to contact import, but in future versions may extend to other objects.
Definition
Parameters
- @param string $object - object being imported (for now Contact only, later Contribution, Activity, Participant and Member)
@param string $object - object being imported (for now Contact only, later Contribution, Activity, Participant and Member) - @param string $usage - hook usage/location (for now process only, later mapping and others)
- @param string $objectRef - import record object
- @param array $params - array with various key values: currently
contactID - contact id
importID - row id in temp table
importTempTable - name of tempTable
fieldHeaders - field headers
Returns
- null
Availability
- This hook was first available in CiviCRM 3.4.1
Example
hook_civicrm_alterAPIPermissions
Description
This hook is called when API 3 permissions are checked and can alter the $permissions structure from CRM/Core/DAO/.permissions.php (as well as the API $params array) based on the $entity and $action (or unconditionally).
Note that if a given entity/action permissions are unset, the default ‘access CiviCRM’ permission is enforced.
Definition
Parameters
- string $entity the API entity (like contact)
- string $action the API action (like get)
- array &$params the API parameters
- array &$permisisons the associative permissions array (probably to be altered by this hook)
Returns
- null
Availability
- This hook was first available in CiviCRM 3.4.1
Example
hook_civicrm_dupeQuery
Description
This hook is called during the dedupe lookup process, and can be used to alter the parameters and queries used to determine if two contacts are duplicates.
The dedupe mechanism is triggered in four places:
- when a CMS user account is created and connected to an existing or new CiviCRM contact;
- during contact imports, where the incoming file records are compared with the existing database;
- when a contact record is created through the interface; and
- when a find duplicate contacts rule is run (comparing a group of contacts or the entire database with itself).
Using the hook parameters, you can isolate how and when your rule modifications are used.
Note that this hook depends upon the existence of a dedupe rule created in the interface in order for it to be called. It works by allowing access to the queries constructed by an interface-create rule.You can modify or completely replace the query or queries that would be run at the point the hook is called, as illustrated below.
You cannot define rule groups with this hook.
Definition
Parameters
- @param string $obj object of rulegroup class
- @param string $type type of queries e.g table / threshold (I'm pretty sure these correspond to strict and fuzzy in the UI)
- @param array $query set of queries
- @access public
Returns
- null
Availability
- Available since 3.3
Example
The example below rewrites the queries for the individual rule group entitled "My Dedupe Rule Group Name" when performing site-wide deduping. It combines six fields into a single query, thus speeding up the duplicate search process.
hook_civicrm_buildStateProvinceForCountry
Description
This hook is called during the ajax callback that is used to build the options that display in the State/Province select widget for a specific country, and can be used to alter the list of State/Province options for particular countries.
Definition
Parameters
- @param string $countryID Country ID for which State/Province data is being looked up
- @param array $states array of State/Province data relating to country being looked up (keys = State/Province ID, values = State/Province name)
Returns
- null
Availability
- Available since 4.1
Example
The example below reorders the Irish State list so that Dublin is at the top of the list (by default, Dublin would be placed in the list in alphabetical order.
Obsolete hooks
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 )