Search code examples
c#sitecoresitecore6sitecore-dms

Sitecore Field Id's vs Field Name's


I read it in "Professional Sitecore Development" book by - John West saying that it's best practice to use Field ID's instead of Field names while getting the Item Field value.

But sitecore Controls like sc:text, sc:link, sc:image etc have an attribute called field which uses field name. So, i am confused now whether to change the whole project to Field ID's or leave it with field names to be consistent with sitecore usage.

Any suggestions will be appreciated.


Solution

  • Yes, Sitecore allows you to use Names and IDs. Also Sitecore allows you to have identical fields names in a same template, what may cause some confusion. IDs, of course, can not be duplicated.

    I believe it is more reliable to use IDs instead of names. Names can easily be changed on Sitecore, and it is hard to find the error when that happens. You won't get compilation error or anything like that until someone notice the field value is not there.

    A good approach is to use a code generator (like T4 or TDS) to create strongly typed classes to be used in your code. Something like:

    public static struct MyTemplate
    {
        public static struct MyGroup1
        {
            public static readonly ID Foo = new ID("{1111111-1111-1231-1231-12312323132}");
        }
        public static struct MyGroup2
        {
            public static readonly ID Foo = new ID("{9999999-9999-xxxx-1231-12312323132}");
        }
    }
    

    Then you go that way on your controls:

    @Html.Sitecore().Field(MyTemplate.MyGroup.Foo); //where foo returns the id.
    

    Hope that helps..