Skip to content

Instantly share code, notes, and snippets.

@chorpo

chorpo/DateField.config

Last active May 24, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.