Fork me on GitHub
Current releases are 2.1.5 (31 Oct 2014) and 2.0.18.13 (5 Aug 2014)

Ready for 2.1? Find out if your plugins are compatible. 2.0 will no longer be updated after Dec 2014.

Display UserPhoto in "Menu"

chjohanchjohan New
edited April 2012 in Vanilla 2.0 Help

I wish to display the users' avatar/userphoto/profilepicture on the left side in the top menu if the user is logged in. I would also like the profilepicture to be a clickable link to the users' profile page.

Is this something that can be done in vanilla/themes/(my_theme)/views/default.master.php? Where do I begin?

Thank you for your time.

Best Answer

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012 Answer ✓

    In the continuing saga you can see which works best for you the one above or this one, if any.

    <?php
    $Session = Gdn::Session();
    if ($Session->IsValid()) {
    if(isset($Session->User->Photo)) {
    $User = UserBuilder($Session->User);
    echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoSmall')) ; 
        }
     }
    

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

    chjohan
«1

Answers

  • mcu_hqmcu_hq yippie ki-yay ✭✭✭
    edited April 2012

    Like this?

    In the traditional plugin , you can extract the code that I used to create that. I made it into a module that you should be able to copy/paste into your own plugin.

    However, I have yet to find a way to actually order the side menu, so sometimes it may appear below other things.

    aerychjohan
  • UnderDogUnderDog Moderator

    mcu_hq said: However, I have yet to find a way to actually order the side menu, so sometimes it may appear below other things.

    Ooohw, that's an interesting side-discussion, maybe for the documentation too :-)

  • Yes, almost like that, mcu_hq. But how do I get the picture to show in the top menu, as I have illustrated below?

    1155277

    I will try to look into your suggested solution with the traditional plugin, but is there not a more straight forward, "simple" way to call the Profile picture?

    Thank you for your answers!

  • UPDATE

    I have now managed to output the users' avatar and username using the following code from the traditional plugin. Thank you, mcu_hq!

           <div>
                <?php $Session = Gdn::Session();
            if ($Session->IsValid()) {
                  echo Img(Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s')), array('width' => '37px', 'height' => '37px')); }?>
            </div>
    
        <div><?php echo $Session->User->Name ?></div> 
    

    I placed the code in my vanilla/themes/(mytheme)/views/default.master.php around line 13. After the <h1><a class="Title>...</a></h1> and before:

        <?php
                          /*$Session = Gdn::Session();*/
                            if ($this->Menu) {
                                $this->Menu->AddLink('Dashboard', T('Dashboard'), '/dashboard/settings', array('Garden.Settings.Manage'));
                                // $this->Menu->AddLink('Dashboard', T('Users'), '/user/browse', array('Garden.Users.Add', 'Garden.Users.Edit', 'Garden.Users.Delete'));
    

    Hope this solution helps others with the same problem.

    Now I have a new question for you. How do I make the user avatar and the echo'ed username link to the user profile page?

  • Also the user avatar gets compressed if it's not in proportion ( a * a)/ 48px * 48px. Is there a way to show the thumbnail of the user?

  • mcu_hqmcu_hq yippie ki-yay ✭✭✭
    edited April 2012

    chjohan said: Also the user avatar gets compressed if it's not in proportion ( a * a)/ 48px * 48px. Is there a way to show the thumbnail of the user?

    yes, I was going to reply to your original one when I'm home. I will give you better code that will solve both of your issues.

    Don't use this: echo Img(Gdn_Upload::Url(ChangeBasename($Sessio.....

    If the user does not have an image, or if you are using Gravatar, you will run into issues. I'll show u in a little bit.

    To create a link to their profile, simply add something like Anchor($User->Name, 'profile/'.$User->ID'/'.$User->Name)

    Also, check out this:

    $Configuration['Garden']['Thumbnail']['Width'] = 90;

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    does this work for you? my once and only attempt. The Anchor(.... above will anchor the name.

    a similar photo function, but this won't give you the larger size you want. another shortcut is UserPhoto($User->Name);

    the one below will give you any size clickable photo you want.

       $PhotoUrl = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s'));
    
                echo   '<a title="'.htmlspecialchars($User->Name).'" href="'.$Href.'"'.$LinkClass.'>'  .Img($PhotoUrl, array('alt' => htmlspecialchars($User->Name), 'class' =>"ProfilePhotoMenu")) .'</a>';
    
    
    add a ProfilePhotoMenu class in css
    with your width and height that you want.
            .ProfilePhotoMenu {
    
            height: 37px;
            width: 37px;
        }
    

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

    422
  • mcu_hqmcu_hq yippie ki-yay ✭✭✭
    edited April 2012

    try this:

    <?php if(isset($Author->Photo)){ $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));} echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>''))?>

    Use this if you need a thumbnail that is larger than 42px. For anything else, use the class, ProfilePhotoSmall/Medium/Large as the ImageClass and no need to prepend the 'p'.

    peregrine
  • peregrineperegrine ☯ hasta luego :) In-Flight MVP

    that's why you're the developer!

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • mcu_hqmcu_hq yippie ki-yay ✭✭✭
    edited April 2012

    AFter looking at your code above, I think you need to always use UserPhoto to avoid the case that the user does not have a photo. This function will call UserPhotoDefaultUrl if the property $User->Photo does not exist.

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    the only thing I was trying to get around was the specific width and height that didn't seem to match the 3 defined classes - small med large . But I like yours less typing. although come to think of it css probably could based on some parent in the menu page, whatever that may be.

    e.g. div or some thing.ProfilePhotoLarge { height: 37px; width: 37px; }

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • mcu_hqmcu_hq yippie ki-yay ✭✭✭
    edited April 2012

    peregrine said: the only thing I was trying to get around was the specific width and height that didn't seem to match the 3 defined classes - small med large . But I like yours less typing. although come to think of it css probably could based on some parent in the menu page, whatever that may be.

    e.g. div or some thing.ProfilePhotoLarge { height: 37px; width: 37px; }

    You can, which is what the main style sheet does for you when in pass in that class.

    You can also just change the thumb size in your configuration to avoid using the very large image: $Configuration['Garden']['Thumbnail']['Size']

    mine defaults to 50, and I needed to use a thumbnail of 96px, so instead of changing the default thumb size to 100px or so, I just use the uploaded image and resize in CSS. This word work for me locally, but I would have to tell people to change their configuration to have theirs not look stretched....and hence just hardcoding in the 'p'.

    Does anyone know how to fix the profile page loading the user image? It does not display anything if they use Gravatar or none at all.

    peregrine
  • mcu_hq said: try this:

    <?php if(isset($Author->Photo)){ $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));} echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>''))?>

    Use this if you need a thumbnail that is larger than 42px. For anything else, use the class, ProfilePhotoSmall/Medium/Large as the ImageClass and no need to prepend the 'p'.

    Thank you for your reply.

    I replaced

     <?php $Session = Gdn::Session();
                if ($Session->IsValid()) {
                      echo Img(Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s')), array('width' => '37px', 'height' => '37px')); }?>
    

    with

    <?php if(isset($Author->Photo)){ $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));} echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>''))?>

    And nothing showed. My whole menu and content disapeared.

    Isn't the **<?php $Session = Gdn::Session(); if ($Session->IsValid()) {... **required to check if the user is logged in? This was my code before the replacement:

                <div id="MenuUserName"><?php echo $Session->User->Name ?></div>        
    
                        <?php
                              /*$Session = Gdn::Session();*/
                                if ($this->Menu) {
                                    $this->Menu->AddLink('Dashboard', T('Dashboard'), '/dashboard/settings', array('Garden.Settings.Manage'));
    

    And now after the replacement:

           <div id="MenuProfilePicture" class="image_wrapper">
    <?php if(isset($Author->Photo)){ $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));} echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>''))?>
                  <div class="topleft"></div>
                  <div class="topright"></div>
                  <div class="bottomleft"></div>
                  <div class="bottomright"></div>
                  </div>
    
        <div id="MenuUserName"><?php echo $Session->User->Name ?></div>        
    
                <?php
                      /*$Session = Gdn::Session();*/
                        if ($this->Menu) {
                            $this->Menu->AddLink('Dashboard', T('Dashboard'), '/dashboard/settings', array('Garden.Settings.Manage'));
    

    Sorry, I'm new to Vanilla and needs to get this explained step by step. Which code to be replaced etc.

    Thank you for your replies guys!

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    Did you try it with session statements in? I beleieve it may have been missing a semi-colon after the echo.

    A quick scan probably this might work. I haven't tried it, but it looks like it will execute what was suggested. This might be easier for you to understand written this way. All statements end in semi-colon and alll php statements must be inside php tags.

    <?php
          $Session = Gdn::Session();
          if ($Session->IsValid()) {
                if(isset($Author->Photo)) { 
                $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));
                } 
           echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>'')) ;
          }
     ?>
    

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • I have now tried your latest suggestion with no success. The user thumbnail just won't show.

                       <div id="MenuProfilePicture" class="image_wrapper">
                    <?php
                    $Session = Gdn::Session();
                    if ($Session->IsValid()) {
                    if(isset($Author->Photo)) {
                    $Author->Photo = Gdn_Upload::Url(ChangeBasename($Author->Photo, 'p%s'));
                    }
                    echo UserPhoto($Author, array('LinkClass'=>'','ImageClass'=>'')) ;
                    }
                    ?>
                              <div class="topleft"></div>
                              <div class="topright"></div>
                              <div class="bottomleft"></div>
                              <div class="bottomright"></div>
                              </div>
    
  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    So , the menu and content still disappeared? Or are you saying thank you the menu and content re-appeared and I still have the problem with the avatar displaying.

    post your entire code, I don't know where you are. and post an image of what you get.

    if it is the User why are you using $author???? try this.

     <?php
        if ($Session->IsValid()) {
         if(isset($Session->User->Photo)) {
          $User->Photo = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s'));
          }
          echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>''));
         }
        ?>
    

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    disregard previous message: this is corrected to get your session

          <?php
            $Session = Gdn::Session();
            if ($Session->IsValid()) {
             if(isset($Session->User->Photo)) {
                  $User->Photo = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s'));
                  }
                  echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>''));
                 }
            ?>
    
    
                for a small photo
    
            echo UserPhoto($User,array('LinkClass'=>'','ImageClass'=>'ProfilePhotoSmall'));
    
    
        for a large photo
    
            echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoLarge'));
    
    
    
        for a custom size photo photo
    
        echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoCustom'));
    
                add a ProfilePhotoCustom class in css
    
                with your width and height that you want.
                    .ProfilePhotoMenu {
                    height: 37px;
                    width: 37px;
                    }
    

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

    chjohan
  • peregrine said: disregard previous message: this is corrected to get your session

    <?php > $Session = Gdn::Session(); > if ($Session->IsValid()) { > if(isset($Session->User->Photo)) { > $User->Photo = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s')); > } > echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'')); > } > ?>

    for a small photo
    echo UserPhoto($User,array('LinkClass'=>'','ImageClass'=>'ProfilePhotoSmall'));

    for a large photo
    echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoLarge'));


    for a custom size photo photo
    echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoCustom'));
    add a ProfilePhotoCustom class in css
    with your width and height that you want. .ProfilePhotoMenu { height: 37px; width: 37px; }

    Thank you. Now the user avatar appears correctly in the menu. Just one little problem: When I click the avatar, it directs me to "http://localhost/vanilla/index.php?p=/profile/0". and I get the "Page not found" message from Vanilla. The correct destiniation for the link is supposed to be "http://localhost/vanilla/index.php?p=/profile/". How do I fix this?

  • My code now looks like this (in vanilla/themes/(mytheme)/views/default.master.php) :

    <?php
    $Session = Gdn::Session();
    if ($Session->IsValid()) {
    if(isset($Session->User->Photo)) {
    $User->Photo = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s'));
    }
    echo UserPhoto($User, array('LinkClass'=>'','ImageClass'=>'ProfilePhotoMenu'));
    }
    ?>
    
  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012
        <?php
        $Session = Gdn::Session();
        if ($Session->IsValid()) {
           if(isset($Session->User->Photo)) {
             $User->Photo = Gdn_Upload::Url(ChangeBasename($Session->User->Photo, 'p%s'));
             $plink = "/profile/" . $Session->User->UserID . "/" . $Session->User->Name;
             echo '<a href="/vanilla/index.php?p=' . $plink . '"/>' ;
             echo ' <img class ="ProfilePhotoSmall" src="' . $User->Photo . '"/>';
          } 
       }
    
     ?>
    

    I don't know if above will show avatars, gravatars, vanillaicons but it should show userphoto. If this doesn't solve your problem, you can probably break out the userphoto fucntion and copy into your theme and modify accordingly (you will see /profile/0 in the userphotos function it to show the profile in functions.render.php.)

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • Both solutions worked well! I went for your last suggestion above because of the user avatar beeing displayed in right proportions without beeing stretched/skewed. Thank you for your time, pregrine! I wish to bother you with one last question.

    What is the exact code for displaying the users' username as a clickable link? My code for displaying the username for now, is: <?php echo $Session->User->Name ?> in default.master.php.

  • chjohan said: What is the exact code for displaying the users' username as a clickable link?

    I managed to do this myself by using: <?php echo UserAnchor($User); ?>

    Thank you all for your answers!

  • peregrineperegrine ☯ hasta luego :) In-Flight MVP
    edited April 2012

    Great. You're learning, just experiment and things gradually become clearer and clearer. whew!

    Monetary Donations will be appreciated if you use my plugins. Thanks in Advance.
    As a waiter gets a tip for a good meal, tips for successful solutions appreciated as well. Peregrine

  • Just used your final solution on my forum - works like a charm, thanks so much for sharing ;)

  • vrijvlindervrijvlinder Jester MVP
    edited March 2013

    This is a great Thread, I was looking for ways to make the user name in the menu display the user image instead of the text/name...Using this method gave me the avatar but not replacing the text link , just added it above the menu. I also pilfered the who's online plugin for snippets but my results have not been satisfactory :(

    I want to add the user image to this link

    $this->Menu->AddLink('User',  $Name,  '/profile/{UserID}/{Username}',array('Garden.SignIn.Allow'), array('class' => 'UserNotifications'));  
    
    

    tried different combos with odd results...what would be the best way to add the user image to that link?

    I thought I could do it like this but I know it is not right:

    $this->Menu->AddLink('User',  Img('unknown link to user photo', array('title' => T('{Username}'),  '/profile/{UserID}/{Username}',array('img class' =>'ProfilePhotoSmall'),array('Garden.SignIn.Allow'), array('class' => 'UserNotifications'));     
    
    
  • KasperKasper Scholar of the Bits Copenhagen Vanilla Staff
    edited March 2013

    A pretty neat Smarty variable was assigned for this sort of stuff: {$User}. It's only accesible through the Smarty templates though, but the function can easily be rewritten so you can use it elsewhere:

    public function User($Sender) {
      $Session = Gdn::Session();
      if($Session->IsValid()) {
         $User = array(
            'Name' => $Session->User->Name,
            'Photo' => '',
            'CountNotifications' => (int)GetValue('CountNotifications', $Session->User, 0),
            'CountUnreadConversations' => (int)GetValue('CountUnreadConversations', $Session->User, 0),
            'SignedIn' => TRUE);
    
         $Photo = $Session->User->Photo;
         if ($Photo) {
            if (!preg_match('`^https?://`i', $Photo)) {
               $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));
            }
         } else {
            if (function_exists('UserPhotoDefaultUrl'))
               $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto');
            elseif ($ConfigPhoto = C('Garden.DefaultAvatar'))
               $Photo = Gdn_Upload::Url($ConfigPhoto);
            else
               $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', TRUE);
         }
         $User['Photo'] = $Photo;
      } else {
         $User = FALSE; /*array(
            'Name' => '',
            'CountNotifications' => 0,
            'SignedIn' => FALSE);*/
      }
      return $User;
    }
    

    Put this in your theme hooks and you can to the following (tried and tested):

    $this->User()['Photo'];
    

    Kasper Kronborg Isager (kasperisager) | Front-end Developer @Vanilla | Hit me up: Google Mail or Vanilla Mail | Find me on GitHub

    422peregrine
  • vrijvlindervrijvlinder Jester MVP

    lol that wiped out everything , I am not getting this treat me like a noob lmao

  • KasperKasper Scholar of the Bits Copenhagen Vanilla Staff
    edited March 2013

    Lol, no worries :-) What you need to do is simply copy/paste the function I posted into your theme hooks inside the []ThemeHooks class:

    <?php if (!defined('APPLICATION')) exit();
    
    class YourThemeHooks implements Gdn_IPlugin {
    
        [User() function goes here]
    
        /**
         * No setup required
         */
        public function Setup() {
            return TRUE;
        }
    
        /**
         * No cleanup required
         */
        public function OnDisable() {
            return TRUE;
        }
    
    }
    

    Then simply write the following to get the profile picture for the currently logged in user:

    $this->User()['Photo'];
    

    ...or if you want to do it directly in the master view (this should work in theory):

    YourThemeHooks::User()['Photo'];
    

    Kasper Kronborg Isager (kasperisager) | Front-end Developer @Vanilla | Hit me up: Google Mail or Vanilla Mail | Find me on GitHub

  • vrijvlindervrijvlinder Jester MVP

    I am able to add the image but what I get is the link not the image lmao Sometimes I get this stuff and sometimes I am lost....this is a php based theme not tpl or smarty. No themehooks except for the master.default.php .. That is where I am trying to put this stuff arg!

«1
Sign In or Register to comment.