Mastering the Sitecore Fields collection

Any Sitecore item contains a list of fields, and this fields collection is accessible through the Fields property on the Sitecore.Data.Items.Item. The Fields property is a FieldCollection.

using Sitecore.Data.Items;
using Sitecore.Data.Fields;

Item myItem = Sitecore.Context.Item;
foreach (Field field in myItem.Fields)
{ 
  Response.Write( field.Name );
}

But the fields collection is not fully instantiated by default. Fields with no value, or fields containing a standard value only is not in the collection.

In order to fully load the fields collection you need to call the ReadAll() function:

Item myItem = Sitecore.Context.Item;
myItem.Fields.ReadAll();
foreach (Field field in myItem.Fields)
{ 
  // The list will now contain all fields
  Response.Write( field.Name );
}

You can also sort the list so all system fields (all fields prefixed with __) is positioned last in the list:

myItem.Fields.Sort();
foreach (Field field in myItem.Fields)
{ 
  // The list is now sorted
  Response.Write( field.Name );
}

The list can be reverted to its default using the Reset() function:

myItem.Fields.ReadAll();
foreach (Field field in myItem.Fields)
{ 
  // The list contain every possible field
  Response.Write( field.Name );
}

myItem.Fields.Reset();
foreach (Field field in myItem.Fields)
{ 
  // The list now only contains fields
  // with values set on the item
  // (no __Standard value values)
  Response.Write( field.Name );
}
Advertisements

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#, Sitecore 6 and tagged , , , . Bookmark the permalink.

One Response to Mastering the Sitecore Fields collection

  1. Vikram says:

    nice article…very helpfull!!!!

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