Monday, October 22, 2012

Accessing the Orchard current user content item

While working on a custom theme for my Orchard based site, I ran into a problem trying to leverage the current user content item. For my theme, I wanted to be able to present some additional information about the current user, from the header in my theme.

Orchard uses Theme modules to separate presentation from content, this separation is one of the (many) reasons I'm starting to really love Orchard. Using a combination of the Designer tools module, and VStudio, you can peruse the shapes displayed on your page. From this I easily replaced the User.cshtml view with my own, but I couldn't work out how to actually reach the current user content item; the default User.html (from ThemeMachine) uses WorkContent.CurrentUser, but this is the IUser not the content item itself!!??

Eventually I stumbled onto: http://orchard.codeplex.com/discussions/255594, and found the user content item is simply WorkerContent.CurrentUser.ContentItem. To keep my site clean, I opted to leverage the Profile module, and add my custom user data to the Profile content part. Then a little prep code in the view, and now I can leverage a custom DisplayName field in my view. I did have to rummage through the source code to find the best way to reach the data using the dynamic type, finally I settled on:

//http://orchard.codeplex.com/discussions/255594
//User controllable display name.
var displayName = String.Empty;
if(WorkContext.CurrentUser != null)
{
  dynamic user = WorkContext.CurrentUser.ContentItem;
  if(user.ProfilePart != null && 
    user.ProfilePart.Has(typeof(object), "DisplayName") &&
    user.ProfilePart.DisplayName.Value is string)
  {
    displayName = user.ProfilePart.DisplayName.Value.Trim();
  }
  
  if(String.IsNullOrWhiteSpace(displayName))
    { displayName = WorkContext.CurrentUser.UserName; }
}

No comments:

Post a Comment

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...