Changing the images for the sitecore search results dynamically

Recently, a request for one of the projects was to change the images in the sitecore search results to be sourced from an image field on the item if it is filled out instead of the default sitecore icons.

The request was also to show these images in the existing views that sitecore comes with by default. I started up with this article from sitecore to create a new view for search: https://doc.sitecore.net/sitecore_experience_platform/developing/develop...

Unfortunately, I had no luck because sitecore has the first two views hard coded in their site for now namely the list and Grid views so I had to come up with a different approach.

Sitecore has a pipeline that it goes through when filling up the items for search. I had to extend this pipeline and manually set the image path to be the image path for the field I wanted to appear. The pipeline name is “buckets.fillItem”.

These are the steps that I have taken:

1. Create a new config entry for my new code that will have the custom logic

<buckets.fillItem>
          <processor patch:after="processor[@type='Sitecore.Buckets.Pipelines.UI.FillItem.ShowFieldValuesInResults, Sitecore.Buckets']" type="MyCode.Library.CustomImageField, MyCode.Library " />
</buckets.fillItem>

2. Implement the custom code

namespace MyCode.Library
{
    public class CustomImageField : FillItemProcessor
    {
        public override void Process(FillItemArgs args)
        {
            //the resultitems are the items that are returned from search
            var resultItems = args.ResultItems.OfType<SitecoreUISearchResultItem>()
            if (resultItems == null)
            {
                return;
            }

            foreach (var sitecoreUiSearchResultItem in resultItems)
            {
                Item sitecoreItem = sitecoreUiSearchResultItem.GetItem();
                //Todo: logic to get the image field from the result item
            }            
        }
    }
}