Raw username token for Drupal 7

29 Oct · by Tim Kamanin · 2 min read

There are situations, when you or other modules alter username via hook_username_alter() and this can change username dramatically: for example, you can alter username into a combination of First and Last Name, etc. Looks nice, but there's a problem, it will alter username into First and Last Name everywhere, even in admin emails being sent out to users upon registration and instead of real username your users will get an altered username in their mail which is sometimes not good.

So what can be done? Hassling with hook_username_alter() and trying to catch cases when you can alter or not username isn't pleasant and here when tokens come to rescue. You can create a custom raw username token which holds unaltered username taken directly from database. Then you can put this token everywhere you need an unaltered username including admin emails.

Let's prepare our custom token, this is simple, put the code below into your custom module (don't forget to replace MODULE_NAME with your module name):

/**
 * Provide information about our custom token.
 */
function MODULE_NAME_token_info() {
  $info['tokens']['user']['name_raw'] = array(
'name' => t('Name: raw'),
'description' => t('Raw username taken straight from DB.'),
  );
  return $info;
}

/**
 * Provide replacement values for placeholder tokens.
 */
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'user' && !empty($data['user'])) {
$user = $data['user'];
foreach ($tokens as $name => $original) {
  switch ($name) {
case 'name_raw':
  $replacements[$original] = $user->name;
  break;
  }
}
return $replacements;
  }
}

And clear the cache. You should now have a User: Name Raw token available in the token list. Put it anywhere you need an unaltered username to be shown and profit! You can find and clone this snippet here: http://dropbucket.org/node/905.

Comments

Required for comment verification



albert_droit

Tim, thanks for the post and the custom module. Everyone can have an opinion, but mine is that in general if you want something simple and avoid performance, updating and maintenance costs, you better use simple yet generic modules. Your solution can be used for this specific functionality of the full name, but also it is a good example for extending it with similar functionalities for other tokens. Cheers!

Reply · 4 years, 1 month ago
Marc Bauer

Don't try this at home. Use the "realname" module and not this custom code.

Reply · 4 years, 1 month ago