Sitecore Field Reference Cheat Sheet

Blog | Technical
Written By: William HubbellPublished On: Oct 01 2019

Fields are at the core of the job of shuttling data from Sitecore to the front end. In Sitecore items, we store our data in fields, and accessing the data in these fields is how we access the database for which Sitecore acts as intermediary.

 

There are multiple field types, each with its own means of access. In this post I intend to create a handy guide that explains how to access some different field types from the back-end. In a later post, I’ll explain what you can do through MVC in the front end.

The most basic way to access an item’s field is to assign its value to a variable, like so:

 

string title = item.Fields["title"].Value;

You could make that a function this way, to include a null check:

 
public static string GetFieldVal(Field field)
{
   if (field != null && field.HasValue)
   {
       return item.Fields[field].Value;
   }
   return "";
}
Then you could simply do the following:

 

string title = GetFieldVal(item.Fields["title"]);

This is the best way to get the value of many different fields, including single-line text fields and droplists.

Image Fields

There are a few ways you can access and render image fields. If you simply use .Value as you might for a text field, you’ll get it’s raw value, which isn’t very useful:

<image mediaid="{DDCD4E35-6A43-4B54-B2E8-74FA23E0B384}" />

One way to access an image field is to use a FieldRenderer in the backend. Doing so will use Sitecore’s rendering engine to translate an image field into Experience Editor-friendly markup. You can do so by using FieldRenderer’s Render method:

 

string imgRendered = FieldRenderer.Render(item, "imagefield");

You can then send imgRendered through the model to the view, and render it using @Html.Raw(Model.ImgRendered), for example.

Another, more common way to access image fields is to directly grab its url and any meta data through an ImageField object. Once you do that, you can use functions like .MediaItem and .Alt to get relevant information. Here’s how you get an image src:

 

public static string GetUrlFromImageField(ImageField field)
{
    string URL = string.Empty;

    //GET IMAGE SOURCE URL
    if (field != null && field.MediaItem != null)
    {
         URL = Sitecore.Resources.Media.MediaManager.GetMediaUrl(field.MediaItem);
    }
    return URL;
}
And you would assign that to a variable, like this:

 

string imgURL = GetUrlFromImageField(item.Fields["image"]);

You could also get the image’s alt field the following way:

 

public static string GetAltFromImageField(ImageField field)
{
    return field != null ? field.Alt : "";
}

string imgAlt = GetAltFromImageField(item.Fields["image"]);

Link Fields

Similar to Image Fields, the raw values of Link Fields aren’t much help to us:

<link linktype="external" url="http://www.wikipedia.com" anchor="" target="" />

 

That’s okay though, because Sitecore has a special LinkField class to help us access attributes of our link fields. Because general link fields have so much data attached to them, such as link types, target, title, in addition to the url itself, the LinkField class is especially crucial to understand.

 

The three options for a general link field are internal, external, and media links. Internal links point to items in the content tree, while media links point to items in the media library. Both of these require special ways to retrieve a normal url. However, external links can be accessed using LinkField’s .Url function.

 

The following function uses LinkField to determine the link type and then access the URL appropriately:

public static string GetUrlFromLinkField(LinkField link)
        {
            string URL = string.Empty;
            string linkType = link.LinkType.ToLower();

            if (linkType == "internal" && link.TargetItem != null)
            {
                URL = Sitecore.Links.LinkManager.GetItemUrl(link.TargetItem);
            }
            else if (linkType == "external")
            {
                URL = link.Url;
            }
            else if (linkType == "media" && link.TargetItem != null)
            {
                URL = Sitecore.Resources.Media.MediaManager.GetMediaUrl(link.TargetItem);
            }

            return URL;
        }
You would assign this to a variable, like so:

 

string url = GetUrlFromLinkField(item.Fields["pageLink"]);

Also like Image fields, Link fields can be rendered using FieldRenderer’s Render method.

Checkbox Fields

Checkbox fields are simple booleans. Their raw values are “1” if checked, and nothing otherwise. However, instead of doing a string check, I recommend using Sitecore’s CheckboxField class, which includes the important .Checked function, which returns a boolean.

 

public static bool IsChecked(CheckboxField field)
        {
            if (field == null)
            {
                return false;
            }

            return field.Checked;
        }

bool checkedOrNot = IsChecked(item.Fields["check"]);

Reference Fields

Some field values reference other items. Droplink fields are good examples of such fields. Unlike droplist fields, the raw values of which are simply the selected text, the raw value of a Droplink field is a string of the GUID of the selected item. If one wants to access that item’s title or any other information from it, one should use Sitecore’s ReferenceField class. You can then use that class’s .TargetItem function to reference fields attached to the droplink selection. This class can be used for Droplinks, Grouped Droplinks, and Droptrees.

 

public static ID GetGUIDFromReferenceField(ReferenceField field)
{
            ID GUIDValue = new ID();

            if(field.TargetItem != null)
            {
                GUIDValue = field.TargetItem.ID;
            }

            return GUIDValue;
}

ID selectionGUID = GetGUIDFromReferenceField(item.Fields["itemSelection"]);

Multi-select Fields

Like Reference fields, Multi-select fields reference Sitecore items directly. Their raw values are simply text strings of multiple pipe-delimited GUIDS. To process these items in a more dynamic way, you’ll want to use a MultilistField class in the back end. You can use that class’s .GetItems function to retrieve an array of Sitecore Items. To manipulate these items, I recommend then creating a List<>, so you can iterate through it with a foreach loop or a LINQ query.

 

public static List<Item> GetMultilist(MultilistField field)
        {
            List<Item> ItemList = new List<Item>();

            if(field != null && field.Count > 0)
            {
                ItemList = field.GetItems().ToList();
            }

            return ItemList;
        }

 

List<Item> MultiList = GetMultiList(item.Fields["multilist"]);

That’s all for now! Let us know if there are other fields you’d like us to talk about, or if you have preferred ways to access fields that we didn’t cover here today.

About the Author
William HubbellSr. Technical Business Analyst
Loading...