1

In Habitat, I defined two templates: _idenity and _footer, and each of them has the same field name but different ID values,for example IDA and IDB.

The start root item inherits both these templates.

So when I use item.Field(IDA) or item.Field(IDB), it always returns the same value. In my case, the field in the _identity template.

When I look deeply in code, the implementation is:

var field = item.Fields[fieldId];
FieldRenderer.Render(item, field.Name)

That means it will get value by name instead of by ID.

Is it possible to get value by ID?

Thanks, Ton

2 Answers 2

1

Is it possible to get value by ID? - Yes

Below is the code to get Sitecore Item Field Value by ID:

var fieldValue= item.InnerData.Fields[new ID(fieldId)];
0
2

This is an improper implementation in Habitat's FieldRendererService. And another reason why you shouldn't start a new (real) project based on that source code. It's really meant as a demo.

You can pass a stringified ID to the FieldRenderer.Render method, which is what should have been done here:

public static string RenderField(Item item, ID fieldId)
{
    var field = item.Fields[fieldId];
    Assert.IsNotNull(field, "Field with id: " + fieldId + " is null on item " + item.Name);
    return FieldRenderer.Render(item, fieldId.ToString());
}

I would also argue that it's a bit strange that the "field ID" variant checks for the field's existence, whereas the name-based variant does not. If you don't do this check, then Sitecore will silently return an empty string if the field doesn't exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.