Last active
August 25, 2016 14:42
-
-
Save soen/66174cce700ce47cd6ff035b457f712f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Sitecore.ContentSearch; | |
using Sitecore.ContentSearch.ComputedFields; | |
using Sitecore.ContentSearch.Utilities; | |
using Sitecore.Data; | |
using Sitecore.Data.Items; | |
namespace Examples.ComputedIndexFields | |
{ | |
public class CombinedDateTime : IComputedIndexField | |
{ | |
public object ComputeFieldValue(IIndexable indexable) | |
{ | |
if (indexable == null) | |
return null; | |
var indexableItem = indexable as SitecoreIndexableItem; | |
if (indexableItem == null) | |
return null; | |
ID templateId = new ID("TemplateId"); | |
// The IsDerived extension method can be found over at: | |
// https://laubplusco.net/sitecore-extensions-does-a-sitecore-item-derive-from-a-template/ | |
if (indexableItem.Item.IsDerived(templateId)) | |
{ | |
DateTime? dateWithTime = GetCombinedDateAndTime(indexableItem.Item); | |
return dateWithTime; | |
} | |
return null; | |
} | |
private DateTime? GetCombinedDateAndTime(Item item) | |
{ | |
DateTime? selectedDate = GetSelectedDate(item); | |
TimeSpan? selectedTime = GetSelectedTime(item); | |
if (selectedDate.HasValue && selectedTime.HasValue) | |
{ | |
DateTime dateWithTime = selectedDate.Value.Add(parsedTime); | |
return dateWithTime; | |
} | |
return null; | |
} | |
private DateTime? GetSelectedDate(Item item) | |
{ | |
DateField dateField = new DateField(item.Fields[new ID("DateFieldId")]); | |
if (string.IsNullOrEmpty(dateField.InnerField.GetValue(true, true))) | |
return null; | |
return dateField.DateTime; | |
} | |
private TimeSpan? GetSelectedTime(Item item) | |
{ | |
string selectedTime = item.Fields[new ID("TimeFieldId")].Value; | |
if (string.IsNullOrEmpty(selectedTime)) | |
return null; | |
TimeSpan parsedTime; | |
if (TimeSpan.TryParse(theTime, out parsedTime)) | |
return parsedTime; | |
return null; | |
} | |
public string FieldName { get; set; } | |
public string ReturnType { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment