Last active
August 22, 2016 16:09
-
-
Save soen/89905ce11cf874f8df9b234e5e997e73 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.Collections.Generic; | |
using System.Linq; | |
using Sitecore.ContentSearch; | |
using Sitecore.ContentSearch.ComputedFields; | |
using Sitecore.ContentSearch.Utilities; | |
using Sitecore.Data; | |
using Sitecore.Data.Items; | |
namespace Examples.ComputedIndexFields | |
{ | |
public class SelectedKeywords : IComputedIndexField | |
{ | |
public object ComputeFieldValue(IIndexable indexable) | |
{ | |
if (indexable == null) | |
return null; | |
var indexableItem = indexable as SitecoreIndexableItem; | |
if (indexableItem == null) | |
return null; | |
IEnumerable<Item> selectedKeywords = GetKeywordsOfSelfAndAncestors(indexableItem); | |
return selectedKeywords.Select(x => IdHelper.NormalizeGuid(x.ID)); | |
} | |
private static IEnumerable<Item> GetKeywordsOfSelfAndAncestors(SitecoreIndexableItem indexableItem) | |
{ | |
List<Item> selectedKeywords = new List<Item>(); | |
Item currentItem = indexableItem.Item; | |
ID keywordFieldId = new ID("ID-TO-KEYWORD-FIELD"); | |
// Here we go up the tree, visiting each ancestor node, and if it | |
// contains the keyword-selector field, we extract the selected | |
// keywords selected and accumulate them to the overall list of | |
// keywords for the given item | |
do | |
{ | |
if (currentItem[keywordFieldId] != null) | |
selectedKeywords.AddRange(new MultilistField(item.Fields[keywordFieldId]).GetItems()); | |
currentItem = currentItem.Parent; | |
} while (currentItem != null); | |
return selectedKeywords; | |
} | |
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