Using field item id to render field contents in Sitecore

Did you know that you can use the field item id for use with the FieldRenderer server control in the FieldName attribute?  For instance, take a look at this sample template item:

Sample Template

Sample Template where “Single Line Text Field” item id is {D2775315-00DC-4CF4-8B68-E9748127D188}

<sc:FieldRenderer ID=”frSingleLineText” runat=”server” FieldName=”{D2775315-00DC-4CF4-8B68-E9748127D188}” Item=”<%# Sitecore.Context.Item %>”></sc:FieldRenderer>

Why would you do this? Well, instead of having to memorize field name you can simply use the field item id.  But a much better reason is because if anyone ever changes the field name then the FieldRenderer will not work whereas if you put the field item id it will still continue to work regardless of how many times someone changes the field name.  You want to stay away from using Field names altogether in your code and stick to using id’s wherever possible.  This is why GlassMapper and other ORM tools are great because they do much of the same similar thing by wrapping up the fields so you can access the template as an object and the fields as a property.  However, sometimes you have to use the traditional Sitecore API to get things done and this is one way to keep code robust.

You can also do this as well in the code behind for a sample Literal control that is going to render the Single Line Text Field contents:

litSingleLineText.Text = myItem[“{D2775315-00DC-4CF4-8B68-E9748127D188}”];

This would require a compile in the solution though.  A better solution is to add the item in the HTML markup and you have a tag that is completely in the presentation and doesn’t need to be compiled when changed.

<sc:FieldRenderer ID=”frSingleLineText” runat=”server” FieldName=”{D2775315-00DC-4CF4-8B68-E9748127D188}” Item=”<%# Sitecore.Context.Item %>”></sc:FieldRenderer>

One thought on “Using field item id to render field contents in Sitecore

  1. kiranpatils

    It is good also, when you Inherit from Templates — And both base template and derived template contains field with same name — You can access using ID — Not an ideal scenario. But I faced this requirement for one specific requirement.

    Kiran

    Reply

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