CiviMail: How to add default values for empty tokens

2009-09-17 22:16
Written by
There was a thread in the forum a few weeks ago about adding generic replacements for tokens that dont have a value for a specific contact. An example is where the first name field is blank and the organization would want to substitute friend or member instead of keeping it blank. The token engine does not provide this functionality by default, however implementing it via a hook is relatively trivial. We use the tokenValues hook to "modify" the token values substituted in any outgoing email. If a contact does not have a token value for a specific token, we just insert the default value. The below code assumes you have a drupal module called civiexample. for joomla change the function name to joomla__civicrm_tokenValues and to standalone_civicrm_tokenValues for standalone.
function civiexample_civicrm_tokenValues( &$values, &$contactIDs ) {
    if ( is_array( $contactIDs ) ) {
        $single = false;
    } else {
        $contactIDs = array( $contactIDs );
        $single = true;

    // lets assume we want default values for the below tokens
    static $defaults = array( 'first_name'  => 'DEFAULT FIRST',
                              'last_name'   => 'DEFAULT LAST',
                              'middle_name' => 'DEFAULT MIDDLE',
                              'home_URL'    => 'HOME URL' );

    foreach ( $contactIDs as $cid ) {
        if ( $single ) {
            $value =& $values;
        } else {
            $value =& $values[$cid];

        foreach ( $defaults as $k => $v ) {
            if ( ! isset( $value[$k] ) || empty( $value[$k] ) ) {
                $value[$k] = $v;
Filed under
Click thumbs up if you thought this blog post was useful (login to vote or to comment)