Wednesday, March 9, 2016

Sitecore accessing items in a computed index field

When the search index is indexing a computed index field for a given item, there is no Sitecore context. This means that if you have code which requires the context of Sitecore - to get an item for example, then there will be a null reference exception.

I found this when I was using a helper class to generate the custom title of my pages - to then be indexed. This class used the context to get a configuration item and therefore was throwing an exception for every page.

The simple solution here is that instead of referencing the context to get an item like follows:
var item = Context.Database.GetItem("Mypath");
You reference the given database directly:
 var webDb = Sitecore.Configuration.Factory.GetDatabase("web");
 var item = webDb.GetItem("MyPath");
This will now get the computed index field working as expected.

No comments:

Post a Comment