How to programmatically add custom markup to every displayed user name
Drupal 8.x
I am currently using hook_preprocess_user().
I would like to alter the username to add some custom markup to every username.
MYMODULE.module:
function MYMODULE_preprocess_user(&$variables) {
$variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}
This returns Name Hello Hello
. Concatenation adds 'Hello' twice so this approach is not working.
I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.
How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.
8 theming users
add a comment |
Drupal 8.x
I am currently using hook_preprocess_user().
I would like to alter the username to add some custom markup to every username.
MYMODULE.module:
function MYMODULE_preprocess_user(&$variables) {
$variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}
This returns Name Hello Hello
. Concatenation adds 'Hello' twice so this approach is not working.
I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.
How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.
8 theming users
In a views preview at/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.
– Prestosaurus
Dec 1 '18 at 5:52
add a comment |
Drupal 8.x
I am currently using hook_preprocess_user().
I would like to alter the username to add some custom markup to every username.
MYMODULE.module:
function MYMODULE_preprocess_user(&$variables) {
$variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}
This returns Name Hello Hello
. Concatenation adds 'Hello' twice so this approach is not working.
I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.
How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.
8 theming users
Drupal 8.x
I am currently using hook_preprocess_user().
I would like to alter the username to add some custom markup to every username.
MYMODULE.module:
function MYMODULE_preprocess_user(&$variables) {
$variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}
This returns Name Hello Hello
. Concatenation adds 'Hello' twice so this approach is not working.
I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.
How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.
8 theming users
8 theming users
edited Dec 1 '18 at 4:10
Prestosaurus
asked Dec 1 '18 at 1:30
PrestosaurusPrestosaurus
530212
530212
In a views preview at/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.
– Prestosaurus
Dec 1 '18 at 5:52
add a comment |
In a views preview at/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.
– Prestosaurus
Dec 1 '18 at 5:52
In a views preview at
/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.– Prestosaurus
Dec 1 '18 at 5:52
In a views preview at
/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.– Prestosaurus
Dec 1 '18 at 5:52
add a comment |
2 Answers
2
active
oldest
votes
Seems hook_user_format_name_alter()
is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use DrupalCoreStringTranslationTranslatableMarkup;
/**
* Implements hook_user_format_name_alter().
*/
function MYMODULE_user_format_name_alter(&$name, $account) {
$name = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if (Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
$name = $variables['title']['#markup']->__toString();
$variables['title'] = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
}
So, what I'd recommend now is, you maybe take the *_preprocess_page_title
hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will useusername.html.twig
template, if you do not link the field it usesviews--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is thathook_preprocess_user()
gets rendered multiple times in some instances.
– Prestosaurus
Dec 3 '18 at 16:54
add a comment |
<?php
use DrupaluserEntityUser;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.
// This example updates the user name.
// $uid is the user id of the user user update
$user = DrupaluserEntityUser::load($uid);
// Don't forget to save the user, we'll do that at the very end of code.
// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.
// The crucial part! Save the $user object, else changes won't persist.
$user->save();
// Congratulations, you have updated a user!
I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, onhook_update_N
? And this doesn't append markup. Only strings seem to be allowed.
– leymannx
Dec 1 '18 at 2:16
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "220"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f273350%2fhow-to-programmatically-add-custom-markup-to-every-displayed-user-name%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Seems hook_user_format_name_alter()
is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use DrupalCoreStringTranslationTranslatableMarkup;
/**
* Implements hook_user_format_name_alter().
*/
function MYMODULE_user_format_name_alter(&$name, $account) {
$name = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if (Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
$name = $variables['title']['#markup']->__toString();
$variables['title'] = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
}
So, what I'd recommend now is, you maybe take the *_preprocess_page_title
hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will useusername.html.twig
template, if you do not link the field it usesviews--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is thathook_preprocess_user()
gets rendered multiple times in some instances.
– Prestosaurus
Dec 3 '18 at 16:54
add a comment |
Seems hook_user_format_name_alter()
is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use DrupalCoreStringTranslationTranslatableMarkup;
/**
* Implements hook_user_format_name_alter().
*/
function MYMODULE_user_format_name_alter(&$name, $account) {
$name = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if (Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
$name = $variables['title']['#markup']->__toString();
$variables['title'] = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
}
So, what I'd recommend now is, you maybe take the *_preprocess_page_title
hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will useusername.html.twig
template, if you do not link the field it usesviews--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is thathook_preprocess_user()
gets rendered multiple times in some instances.
– Prestosaurus
Dec 3 '18 at 16:54
add a comment |
Seems hook_user_format_name_alter()
is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use DrupalCoreStringTranslationTranslatableMarkup;
/**
* Implements hook_user_format_name_alter().
*/
function MYMODULE_user_format_name_alter(&$name, $account) {
$name = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if (Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
$name = $variables['title']['#markup']->__toString();
$variables['title'] = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
}
So, what I'd recommend now is, you maybe take the *_preprocess_page_title
hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
Seems hook_user_format_name_alter()
is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use DrupalCoreStringTranslationTranslatableMarkup;
/**
* Implements hook_user_format_name_alter().
*/
function MYMODULE_user_format_name_alter(&$name, $account) {
$name = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if (Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
$name = $variables['title']['#markup']->__toString();
$variables['title'] = new TranslatableMarkup('@name <span class="foo-bar">Foo Bar</span>', ['@name' => $name]);
}
}
So, what I'd recommend now is, you maybe take the *_preprocess_page_title
hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
edited Dec 1 '18 at 2:33
answered Dec 1 '18 at 2:27
leymannxleymannx
6,92852659
6,92852659
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will useusername.html.twig
template, if you do not link the field it usesviews--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is thathook_preprocess_user()
gets rendered multiple times in some instances.
– Prestosaurus
Dec 3 '18 at 16:54
add a comment |
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will useusername.html.twig
template, if you do not link the field it usesviews--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is thathook_preprocess_user()
gets rendered multiple times in some instances.
– Prestosaurus
Dec 3 '18 at 16:54
1
1
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will use
username.html.twig
template, if you do not link the field it uses views--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is that hook_preprocess_user()
gets rendered multiple times in some instances.– Prestosaurus
Dec 3 '18 at 16:54
+1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will use
username.html.twig
template, if you do not link the field it uses views--field.html.twig
template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is that hook_preprocess_user()
gets rendered multiple times in some instances.– Prestosaurus
Dec 3 '18 at 16:54
add a comment |
<?php
use DrupaluserEntityUser;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.
// This example updates the user name.
// $uid is the user id of the user user update
$user = DrupaluserEntityUser::load($uid);
// Don't forget to save the user, we'll do that at the very end of code.
// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.
// The crucial part! Save the $user object, else changes won't persist.
$user->save();
// Congratulations, you have updated a user!
I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, onhook_update_N
? And this doesn't append markup. Only strings seem to be allowed.
– leymannx
Dec 1 '18 at 2:16
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
add a comment |
<?php
use DrupaluserEntityUser;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.
// This example updates the user name.
// $uid is the user id of the user user update
$user = DrupaluserEntityUser::load($uid);
// Don't forget to save the user, we'll do that at the very end of code.
// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.
// The crucial part! Save the $user object, else changes won't persist.
$user->save();
// Congratulations, you have updated a user!
I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, onhook_update_N
? And this doesn't append markup. Only strings seem to be allowed.
– leymannx
Dec 1 '18 at 2:16
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
add a comment |
<?php
use DrupaluserEntityUser;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.
// This example updates the user name.
// $uid is the user id of the user user update
$user = DrupaluserEntityUser::load($uid);
// Don't forget to save the user, we'll do that at the very end of code.
// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.
// The crucial part! Save the $user object, else changes won't persist.
$user->save();
// Congratulations, you have updated a user!
I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
<?php
use DrupaluserEntityUser;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.
// This example updates the user name.
// $uid is the user id of the user user update
$user = DrupaluserEntityUser::load($uid);
// Don't forget to save the user, we'll do that at the very end of code.
// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.
// The crucial part! Save the $user object, else changes won't persist.
$user->save();
// Congratulations, you have updated a user!
I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
edited Dec 1 '18 at 2:16
answered Dec 1 '18 at 2:08
hotwebmatterhotwebmatter
457112
457112
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, onhook_update_N
? And this doesn't append markup. Only strings seem to be allowed.
– leymannx
Dec 1 '18 at 2:16
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
add a comment |
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, onhook_update_N
? And this doesn't append markup. Only strings seem to be allowed.
– leymannx
Dec 1 '18 at 2:16
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
1
1
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, on
hook_update_N
? And this doesn't append markup. Only strings seem to be allowed.– leymannx
Dec 1 '18 at 2:16
Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, on
hook_update_N
? And this doesn't append markup. Only strings seem to be allowed.– leymannx
Dec 1 '18 at 2:16
1
1
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)
– hotwebmatter
Dec 1 '18 at 2:20
add a comment |
Thanks for contributing an answer to Drupal Answers!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f273350%2fhow-to-programmatically-add-custom-markup-to-every-displayed-user-name%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
In a views preview at
/admin/structure/views/view/view_name
and a views page, it appears to render ok. I have been testing via a referenced views block.– Prestosaurus
Dec 1 '18 at 5:52