Create tokens for profile fields Drupal 6

by John McGeechan

Synopsis


 How to add profile fields to the token logic

 

 

Overview

Two hooks are required..

  • hook_token_list to add fields to the list of available tokens
  • hook_token_values to provide the values for those fields

 

Here's some code I prepared earlier....

 

// list the available profile fields
function yourmodule_token_list($type = 'all') {
    if ($type == 'user' || $type == 'all') {
        $tokens = yourmodule_tokenLogic();
        foreach ($tokens as $key => $value) {
          // only interested in the keys at this point
            $tokens['profile'][$key]      = t("profile field - $key");
        }
        return $tokens;
    }
}

// get value for the available profile fields
function yourmodule_token_values($type, $object = NULL, $options = array()) {
    if ($type == 'user') {
        $tokens = yourmodule_tokenLogic($object->uid);
        foreach ($tokens as $key => $value) {
          // keys and values
            $tokens['profile'][$key] = $value;
        }
        return $tokens;
    }
}

// main logic
function yourmodule_tokenLogic($userid = '',$listOrValue = 'value') {
    
    $profileTokens = array();
    
    /*
     * probably overzealous belt and braces checks !
     */
    if(!$userid) {
        global $user;
        if($user && is_object($user) && !(empty($user->uid))) {
            $userid = $user->uid;
        } else {
            return $profileTokens;
        }
    };    
            
    if(is_int((int)$userid)) {
        $account = user_load($userid);
    } else {
        return $profileTokens;
    }
    
    // look for profile fields and place in the array
    if(is_object($account)) {
        $profileproperties = array();
        foreach(array_keys((array)$account) as $property) {
            if (strpos($property,'profile_') === 0 ) {
                $profileTokens[$property] = $account->{$property};
            }
        }
            
    }
    
    return $profileTokens;
    
}

 

Post new comment

By submitting this form, you accept the Mollom privacy policy.