Friday 23 May 2014

How to get collection of fields that exists within a section of Sitecore item

2 comments
In this blog post I am going to explain how to retrieve collection of fields that exists within a section of Sitecore item. For example: I am having a template named as Article. In Article template I am having two sections: News Text and News Image. Every section is having few specific fields associated with it. I’ve created a Sitecore item based on Article template. I want to access specific fields of given section name in this Sitecore item.
Figure: Article Template
Below function GetFieldsWithInSection(string itemId, string sectionName) takes Sitecore item id and section name and returns dictionary collection. Field name is set as Dictionary Key and Field value is set as Dictionary Value.
public Dictionary<string,string> GetFieldsWithInSection(string itemId, string sectionName)
        {
            Dictionary<string, string> FieldsWithInSection = new Dictionary<string, string>();
            if (Sitecore.Data.ID.IsID(itemId))
            {
                Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));
                if (item != null)
                {
                  FieldsWithInSection = item.Fields.Where(name => name.Section == sectionName).ToDictionary(field => field.Name, field => field.Value);
                }
            }
            return FieldsWithInSection;
        }
Example:
string itemId={560CFE39-D932-4FB7-A39F-0E335375439E};
string sectionName = "News Text";

Dictionary<string, string> FieldsWithInSection  = GetFieldsWithInSection(itemId,sectionName );
Comments and suggestions are most welcome. Happy coding!

2 comments :

  1. I cant see a reason REMOTE_ADDR will not give you the correct user ip address.
    if the user was redirected by a NLB(Network Load Balance) or by a simple redirection page, he will still make the new HTTP request from his own machine.
    So the REMTOTE_ADDR header will give you a right information.

    ReplyDelete
  2. Thanks for commenting Hagai. :)
    It depends on how Load Balancer is configured. I'd checked few online resources about it. I've found one good MSDN article about it. http://msdn.microsoft.com/en-us/magazine/cc163692.aspx

    ReplyDelete