Sitecore 5.3: Those darn links

The new link field in Sitecore 5.3 i pretty cool. You can inset links/media library links/external links and so on by choosing the appropriate link style from the context menu.
Choosing the correct link type from the context menu allows you to use the control in your XSLT’s.

But what if the user does’nt choose the correct link type? What if he just inserts an internal link that is pointing to a media library item? Then the will make a link to the media library item and not the actucal document contained in the media library.

Well, we have to code here. This function takes the GUID of a Sitecore node and a field name. The field name is the name of the Link field on the node. The function will return the absolute path of the item linked to, even if the item is a media library item:

public string LinkToAbsolutePath(string itemID, string field)
  Item item = Sitecore.Context.Database.GetItem( new Sitecore.Data.ID(itemID) );
  if (item == null)
    throw new NullReferenceException( itemID + " not found" );
  Sitecore.Data.Fields.LinkField lf = item.Fields[field];
  if (lf.IsMediaLink)
    return lf.TargetItem["Path"];
  if (lf.IsInternal)
    if ( lf.TargetItem.TemplateName.ToLower() == "file" )
      return lf.TargetItem["Path"];
    return lf.TargetItem.Paths.GetFriendlyUrl();
  return lf.Url;

The first few lines of code gets the correct Sitecore item, and the link field.
The first if statement checks to see if the links is a media library link. If so I return the value of the target item’s “Path” field. You would have assumed that the media library item path is the lf.MediaPath, but ohh no, this is just the Sitecore node name.
The next if statement checks to see if the link is an internal link. Then I check to see if the target item points to a file template, or inheriting from a file template. Media library items are actually not based on the file template, they inherit from it. If it is a file template, again return the “path” field contents, not the MediaPath. I inheritance is not of file, I return the friendly URL.
The default return value is the Url field, which is hit if the link is an external type.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 5 and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s