Sitecore

Getting standard Sitecore fields as a list?

I had a task where I needed to get field names present on an item. By getting all fields on an item using Item.Fields, I could easily convert this list to a list of strings, containing the name of the field:

var fieldNames = contextItem.Fields.Select(field => field.Name).ToList();

In my case the client would provide a exclude pipe-separated list of item names which we didn’t need for this operation:

Exlucde

Removing these values:

var excludedFields = templateFieldValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
// Removed excludes.
foreach (string fieldName in excludedFields)
{
     fieldNames.RemoveAll(x => x.ToLower().Equals(fieldName.ToLower()));
}

However, this will leave you with a list of custom fields for the item, along with standard fields from Sitecore. In our case we needed to have a complete list of custom fields, without Sitecores standard fields.

To achieve this, Sitecore has a static class which contains all of the standard fields for Sitecore:

Sitecore.FieldIDs

This class has 82 fields, which return a Sitecore.Data.ID. I needed a list of those IDs, so I could filter my field names, and remove all unneeded fields. To get this list you can use reflection:

/// <summary>
/// Use reflection to get all sitecore standard field ids from FieldIDs class
/// </summary>
/// <returns>List of Sitecore standard fields IDs</returns>
private static List<ID> GetStandardSitecoreFields()
{
     Type myType = typeof(FieldIDs);
     FieldInfo[] fields = myType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
     return fields.Select(field => (ID) field.GetValue(myType)).ToList();
}

With this list you can easily remove Sitecore standard fields, when using Item.Fields:

var fieldNames = contextItem.Fields.Where(f => !sitecoreStandardFieldIDs.Contains(f.ID)).ToList().Select(field => field.Name).ToList();
Advertisements

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 )

Google+ photo

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

Connecting to %s