Creation of custom tokens / placeholder for Drupal 7. I searched many forums to get any help regarding the creation of custom tokens but I failed in getting a proper solution that's why I decided to post this topic to help drupal users.
- hook_token_info
- hook_tokens($type, $tokens, array $data = array(), array $options = array())
- token_replace($text, array $data = array(), array $options = array())
For creating custom token we will use three token api function.
<?php
/**
* Implements hook_token_info(). This hook will register tow token lname and fname.
*/
function myhook_token_info() {
$info['tokens']['custom']['fname'] = array(
'name' => t('First name'),
'description' => t('First name re placer for fname '),
);
$info['tokens']['custom']['lname'] = array(
'name' => t('Last name'),
'description' => t('Last name re placer for lname '),
);
return $info;
}
/**
* Implements hook_tokens(). This hook will operate the token and replace it with it's value.
*/
function myhook_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();
$sanitize = !empty($options['sanitize']);
if ($type == 'custom') {
foreach ($tokens as $name => $original) {
if (array_key_exists($name, $data)) {
$replacements[$original] = $data[$name];
}
}
}
return $replacements;
}
/**
* Here we will use the token_replace() function to get the actual content after replacement.
*/
function myhook_myfunction() {
$custom = array();
$custom['fname'] = 'Rajat';
$custom['lname'] = 'Gusain';
$data = $custom;
$temp = "Full name : [custom:fname] [custom:lname]";
$temp = token_replace($temp, $data);
// After token replacement $temp variable will contain " Full name : Rajat Gusain"
}
?>