Counting Fields

Counting Fields

Controls featured in this example:

  • Sitecore Web Control
  • Classes featured in this example:

  • Sitecore.Collections.FieldCollection
  • Sitecore.Context
  • Sitecore.Data.Fields.Field
  • Sitecore.Data.Items.Item
  • Counting Fields C# Web Control Code

    Sitecore.Data.Items.Item item = this.GetItem();
    if (item == null) return;

    Sitecore.Context.Item.Fields.ReadAll();
    Sitecore.Collections.FieldCollection fields = item.Fields;
    if (fields == null) return;

    output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
    output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
    output.Write("C# Web Control Real-time Output");
    output.RenderEndTag();

    output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
    output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
    output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
    output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
    //using : for colon and   for space
    output.Write("{0}: {1}", "Item", item.DisplayName);
    output.RenderEndTag(); //P

    int i = 0, j = 0, k = 0;
    foreach (Sitecore.Data.Fields.Field field in fields)
    {
       if (field.Name.StartsWith("__"))
    i++;
       else if (field.Type == "Single-Line Text")
       j++;
       else
       k++;
       }
    output.Write("{0}&#58;&#160;{1}", "Total Field Count", "<b>" + item.Fields.Count.ToString() + "</b><br/>");
    output.Write("{0}&#58;&#160;{1}", "Standard Fields", "<b>" + i.ToString() + "</b><br/>");
    output.Write("{0}&#58;&#160;{1}", "Single-Line Text Fields", "<b>" + j.ToString() + "</b><br/>");
    output.Write("{0}&#58;&#160;{1}", "Other Non-Standard Fields", "<b>" + k.ToString() + "</b>");
    output.RenderEndTag(); //Div


    Counting Fields C# Web Control Output

    Total Field Count: 75
    Standard Fields: 57
    Single-Line Text Fields: 5
    Other Non-Standard Fields: 13

    Notes

    • Use a double underscore prefix to filter the Sitecore Standard Fields