Saturday, January 17, 2009

Friday Gotcha: Sitecore.Data.Items.Item.Fields


For the sake of performance, Sitecore will not give you all fields in the FieldCollection in the following code, only fields with explicit values on item level, including empty string:

foreach(Sitecore.Data.Fields.Field field in Sitecore.Context.Item.Fields)
{
  // here you will see only fields with values (even empty string) set on item level
  // fields with null in them or standard values will not be here.
}

However, you will be able to access fields with either Sitecore.Context.Item.Fields["title"] or with a PageEditor enabled Web Control such as sc:text: <sc:text field="title" runat="server" />

In order to have all the fields in the FieldCollection and iterate through them, make sure your code will include Sitecore.Data.Items.Item.Fields.ReadAll() call before your foreach:

Sitecore.Context.Item.Fields.ReadAll();
foreach(Sitecore.Data.Fields.Field field in Sitecore.Context.Item.Fields)
{
  // do your thing here
}

FAQ about this.

3 comments:

Sean said...

Hi Alex,
Quite a "smell" to be honest.
Is this still a case?

Thank you.

Alex Shyba said...

Hi Sean,

As far as I can see, this is still the case for the latest version.

You can file a support ticket with a product change request via the support portal. I have not found this registered as a feature request yet.

Or if you do not have access, contact me at AS at sitecore dot net and I will file it for you.

-alex

Maulik said...

Hi Alex,
We faced the similar issue. We are using Sitecore 6.5.
We define the Field id as a string in the constant and then using itmCurrent.Field[constfieldName] we get the field and if the field is not null then get the Value.

public const string NoResultsText = "{ID of the Field}";


This is working on all pages but some how on one page we were not able to get the value of a particular field. when we tried to get the value using index it was working fine but not with the name.

In quickwatch we got the .value as "" but data was stored in inheritedvalue.

We tried the ReadAll path that also didn't work.

Following worked:
var field = itmCurrent.Fields[new Sitecore.Data.ID(Globals.Field.NoResultsText)];

Can you please suggest if we are missing anything? Why for just one field the approach is not working?