Sitecore LinkField TargetItem is NULL – what’s wrong?

An ancient topic, that pops up once or twice every year. The TargetItem of Sitecore.Data.Links.LinkField returns NULL and you are CERTAIN that the item is published. What to do?

CASE 1: THERE IS SECURITY SET ON THE TARGETITEM

Items where extranet\Anonymous does not have read access, the item will exist in the WEB database, but is not available by the calling user, and the return value is NULL.

The solution is simple, use the SecurityDisabler before reading the LinkField:

using (new SecurityDisabler())
{
    LinkField linkField = myItem.Fields["myfield"];
    if (linkField != null && linkField.TargetItem != null)
    {
      // do stuff
    }
  }
}

CASE 2: YOU FROGOT TO PUBLISH THE TEMPLETE

The item is published, but the item template is not. Go to the WEB database and find the item. If there is no fields on the item, the template is most likely missing. Remember to publish the template.

CASE 3: THE LINKFIELD IS POINTING TO AN EXTERNAL URL

The LinkField have a LinkType. If the LinkType is “internal“, the targetitem is valid. If the LinkType is “external“, you have added an external url, and you need to read the “Url” property instead.

Click here to get a method that gives you the correct link regardless of the linktype.

CASE 4: THE LINKFIELD IS POINTING TO A MEDIA LIBRARY ITEM

The TargetItem is not NULL, but it is poiting to the media libray item which have no URL. Instead, you need to use the MediaManager to get the URL of the media item.

Click here to see how to use the MediaManager.

CASE 5: THE ITEM IS ACTUALLY NOT PUBLISHED

Ahh, the most embarrassing situation. You published the item with the LinkField, but not the item that the LinkField is pointing to.

Don’t worry. This happens to all of us. More than once.

MORE TO READ:

 

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET, Sitecore, Sitecore 6, Sitecore 7, Sitecore 8, Sitecore 9 and tagged , , , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.