Skip to content

Instantly share code, notes, and snippets.

@chorpo
Last active May 24, 2019 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chorpo/eebf5a0feb9f79995d0ace2064ebe907 to your computer and use it in GitHub Desktop.
Save chorpo/eebf5a0feb9f79995d0ace2064ebe907 to your computer and use it in GitHub Desktop.
Sitecore Custom Computed Date Field
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<CustomIndexConfiguration type="ToTheCoreSk.SC.Foundation.Search.AlgoliaIndexConfiguration, ToTheCoreSk.SC.Foundation.Search">
<DocumentOptions type="Sitecore.ContentSearch.DocumentBuilderOptions, Sitecore.ContentSearch">
<fields hint="raw:AddComputedIndexField">
<field fieldName="Date" referencedFieldName="__Updated" dateFormatPattern="yyyyMMdd">ToTheCoreSk.SC.Foundation.Search.ComputedFields.DateField, ToTheCoreSk.SC.Foundation.Search</field>
</fields>
</DocumentOptions>
</CustomIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
using System.Globalization;
using System.Xml;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.ComputedFields;
using Sitecore.ContentSearch.Diagnostics;
using Sitecore.Xml;
namespace ToTheCoreSk.SC.Foundation.Search.ComputedFields
{
public class DateField : IComputedIndexField
{
public DateField(XmlNode configurationNode)
{
FieldName = XmlUtil.GetAttribute("fieldName", configurationNode);
ReferencedFieldName = XmlUtil.GetAttribute("referencedFieldName", configurationNode);
DateFormatPattern = XmlUtil.GetAttribute("dateFormatPattern", configurationNode);
}
public string FieldName { get; set; }
public string ReturnType { get; set; }
public string ReferencedFieldName { get; set; }
public string DateFormatPattern { get; set; }
public virtual object ComputeFieldValue(IIndexable indexable)
{
var item = (SitecoreIndexableItem)indexable;
if (item?.Item == null)
{
CrawlingLog.Log.Error("DateField: indexable is not provided");
return string.Empty;
}
if (string.IsNullOrEmpty(FieldName))
{
CrawlingLog.Log.Error("DateField: FieldName is not provided");
return string.Empty;
}
var field = (Sitecore.Data.Fields.DateField)item.Item.Fields[ReferencedFieldName];
if (field == null)
{
CrawlingLog.Log.Debug($"DateField: Cannot find field '{ReferencedFieldName}'");
return string.Empty;
}
if (string.IsNullOrEmpty(DateFormatPattern))
{
CrawlingLog.Log.Debug($"DateField: DateFormatPattern is not provided");
return string.Empty;
}
return field.DateTime.ToString(DateFormatPattern, CultureInfo.InvariantCulture);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment