Passing Custom Parameters to Computed Fields
Passing Custom Parameters to Computed Fields
Sometimes, you may want to pass custom parameters to a computed field. For example, following the Creating a Computed Date Field tutorial, you may want to control when the archivedate
field is created on items. For this purpose, the current tutorial shows you how to configure the number of days before an item is archived.
Requirements
- You have completed the Creating a Computed Date Field tutorial before.
Steps
- Using Visual Studio, open the
ComputedDateField
class. -
Add a constructor to accept additional XML configuration.
private readonly XmlNode m_Configuration; public ArchiveDateField(XmlNode p_Configuration) { m_Configuration = p_Configuration; }
-
Add a method to parse the configuration XML attributes and return their value.
protected string GetConfigurationValue(string p_ConfigurationKey) { string configurationValue = null; if (m_Configuration != null && m_Configuration.Attributes != null) { XmlAttribute configurationAttribute = m_Configuration.Attributes[p_ConfigurationKey]; if (configurationAttribute != null) { configurationValue = configurationAttribute.Value; } } return configurationValue; }
-
Add a property to retrieve the configuration value formatted as an integer.
protected int DaysBeforeArchiving { get { int daysCount; if (!Int32.TryParse(GetConfigurationValue("daysBeforeArchiving"), out daysCount)) { daysCount = 365; // One year by default } return daysCount; } }
-
Change the
ComputeFieldValue
method to use theDaysBeforeArchiving
property./// <inheritdoc /> public object ComputeFieldValue(IIndexable p_Indexable) { SitecoreIndexableItem indexableItem = p_Indexable as SitecoreIndexableItem; if (indexableItem != null) { IIndexableDataField dateField = indexableItem.GetFieldByName(SITECORE_CREATED_FIELD); if (dateField != null) { DateTime itemCreationDate = DateUtil.ParseDateTime(dateField.Value.ToString(), DateTime.MaxValue); return itemCreationDate.AddDays(DaysBeforeArchiving).ToString(COVEO_INDEX_DATE_FORMAT); } } return null; }
-
Compile your project.
-
Copy the resulting assembly (
Coveo.Custom.dll
) to thebin
folder of your Sitecore instance. -
Open your
Coveo.SearchProvider.Custom.config
file and add thedaysBeforeArchiving
parameter as an XML attribute.<field fieldName="archiveDate" daysBeforeArchiving="30">Coveo.Custom.ArchiveDateField, Coveo.Custom</field>
- Rebuild your indexes using the Indexing Manager (Sitecore Desktop > Start Menu > Control Panel > Indexing > Indexing Manager).
-
Validate that your computed field now uses the
DaysBeforeArchiving
parameter by following the validation steps described in step 3 of Creating a Computed Date Field. There should be a difference of 30 days between both dates.