How to programmatically add custom markup to every displayed user name





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty{ margin-bottom:0;
}






up vote
1
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
    40 mins ago



















up vote
1
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
    40 mins ago















up vote
1
down vote

favorite









up vote
1
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 2 hours ago

























asked 5 hours ago









Prestosaurus

463111




463111












  • 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
    40 mins ago




















  • 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
    40 mins ago


















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
40 mins ago






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
40 mins ago












2 Answers
2






active

oldest

votes

















up vote
1
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
    4 hours ago








  • 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.)
    – Matt Obert
    4 hours ago


















up vote
1
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























    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
    1
    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
      4 hours ago








    • 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.)
      – Matt Obert
      4 hours ago















    up vote
    1
    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
      4 hours ago








    • 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.)
      – Matt Obert
      4 hours ago













    up vote
    1
    down vote










    up vote
    1
    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 4 hours ago

























    answered 4 hours ago









    Matt Obert

    268110




    268110








    • 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
      4 hours ago








    • 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.)
      – Matt Obert
      4 hours ago














    • 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
      4 hours ago








    • 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.)
      – Matt Obert
      4 hours ago








    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
    4 hours ago






    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
    4 hours ago






    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.)
    – Matt Obert
    4 hours ago




    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.)
    – Matt Obert
    4 hours ago












    up vote
    1
    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



























      up vote
      1
      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

























        up vote
        1
        down vote










        up vote
        1
        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 3 hours ago

























        answered 4 hours ago









        leymannx

        6,58842657




        6,58842657






























            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

            Understanding the information contained in the Deep Space Network XML data?

            Ross-on-Wye

            Eastern Orthodox Church