Question

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.

Was it helpful?

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..

OTHER TIPS

As an FYI adding to @RobertoBr's excellent answer, Sitecore uses GUIDs internally to access well known fields. If you decompile Sitecore.Kernel.dll and look in the static class Sitecore.FieldIDs you will see a list of fields you would be very familiar with using, e.g.

public static ID Created = new ID("{25BED78C-4957-4165-998A-CA1B52F67497}");
public static ID CreatedBy = new ID("{5DD74568-4D4B-44C1-B513-0AF5F4CDA34F}");
public static ID DisplayName = new ID("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}");

Very similar to what RobertoBr has suggested.

I would recommend you to use field IDs instead of field names in all cases.

  1. Field IDs usage prevents a lot potential mistakes, misspell, etc..

  2. You don't need to worry about correct behavior if you will decide to rename some fields (or other developer will decide to rename his fields).

  3. If you use template's inheritance, you may have potential bugs with duplicates of field names.

  4. Field IDs usage prevents unnecessary processing. Because when you are using field name, Sitecore resolves field ID by field name and after that retrieves field by ID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top