How to programmatically add custom markup to every displayed user name











up vote
2
down vote

favorite












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.










share|improve this question
























  • 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 at 5:52

















up vote
2
down vote

favorite












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.










share|improve this question
























  • 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 at 5:52















up vote
2
down vote

favorite









up vote
2
down vote

favorite











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.










share|improve this question















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 1 at 4:10

























asked Dec 1 at 1:30









Prestosaurus

490111




490111












  • 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 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 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 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 at 5:52












2 Answers
2






active

oldest

votes

















up vote
3
down vote













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.






share|improve this answer



















  • 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 at 16:54


















up vote
0
down vote













<?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






share|improve this answer



















  • 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 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 at 2:20











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',
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
});


}
});














draft saved

draft discarded


















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








up vote
3
down vote













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.






share|improve this answer



















  • 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 at 16:54















up vote
3
down vote













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.






share|improve this answer



















  • 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 at 16:54













up vote
3
down vote










up vote
3
down vote









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.






share|improve this answer














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.







share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 1 at 2:33

























answered Dec 1 at 2:27









leymannx

6,74842658




6,74842658








  • 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 at 16:54














  • 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 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 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 at 16:54












up vote
0
down vote













<?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






share|improve this answer



















  • 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 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 at 2:20















up vote
0
down vote













<?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






share|improve this answer



















  • 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 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 at 2:20













up vote
0
down vote










up vote
0
down vote









<?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






share|improve this answer














<?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







share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 1 at 2:16

























answered Dec 1 at 2:08









hotwebmatter

423111




423111








  • 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 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 at 2:20














  • 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 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 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 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 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 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 at 2:20


















draft saved

draft discarded




















































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.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • 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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Ellipse (mathématiques)

Quarter-circle Tiles

Mont Emei