sitecoresitecore8sitecore7sitecore8.2

Sitecore 8 easy way to get Item in internal link?


I have several General Link Fields, that are used as internal Links, so a Sitecore Item.

I need that "target" Items in my code, and I have the feeling that I am doing it in a horrible complex way:

LinkField lf = myItem.Fields["My Link"];
if (lf != null)
{
    if (lf.Value != null)
    {
        ID targetID;
        if (ID.TryParse(lf.Value, out targetID))
        {
            Item targetItem = Sitecore.Context.Database.GetItem(targetID);
            {
                if (targetItem != null)
                {
                    // go on with code
                }
            }
        }
    }
}

Does someone know a more easy way to get this target Item?

Regards


Solution

  • You can use TargetItem property of the LinkField without custom code:

    Item targetItem;
    
    LinkField linkField = myItem.Fields["My Link"];
    if (linkField != null && linkField.IsInternal)
    {
        targetItem = linkField.TargetItem;
    }