Out of the box, Sitecore comes with the following expand standard values tokens:
$name – Name of the item
$date – Current server date
$time – Current server time
$now – Current server date time
$id – Item ID
$parentid – Item’s Parent ID
$parentname – Item’s Parent Name
Sometimes the already existing tokens are not enough. There are cases in which the Content Editors won`t be able to access the value that needs to be populated (ex. – web service call) or it will be hard for them to do it (ex. – the value of the item varies on many other items). In the current example, the $next token will be implemented. It will automatically replace the token with the current siblings' count plus one – this token is usually used in cases where there is a requirement for the auto-incrementing sort order of items.
Implementing a custom token is fairly simple and can be achieved in 2 easy steps.
Step 1 – Creating a custom ExpandInitialFieldValueProcessor
Create a custom ExpandInitialFieldValueProcessor with the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Pipelines.ExpandInitialFieldValue;
namespace SitecoreMaster82.Models.CustomToken
{
public class TokenNextProcessor : ExpandInitialFieldValueProcessor
{
public override void Process(ExpandInitialFieldValueArgs args)
{
if (args.SourceField.Value.Contains("$next"))
{
if (args.TargetItem != null && args.TargetItem.Parent != null && args.TargetItem.Children != null)
{
args.Result = args.Result.Replace("$next", args.TargetItem.Parent.Children.Count.ToString());
}
else
{
args.Result = args.Result.Replace("$next", "0");
}
}
}
}
}
The code is pretty straightforward. It checks if the value of the field contains the $next token. If it does it checks if the parent is not null and the parent has children. If the parent is not null and there are children the value is set to the children`s count (the processor is executed after the child is added to the index will be 1 based), otherwise it sets the value to 0.
Step 2 – Creating the custom configuration
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<expandInitialFieldValue>
<processor type="SitecoreMaster82.Models.CustomToken.TokenNextProcessor , SitecoreMaster82"
patch:after="processor[@type='type=Sitecore.Pipelines.ExpandInitialFieldValue.ReplaceVariables, Sitecore.Kernel']" />
</expandInitialFieldValue>
</pipelines>
</sitecore>
</configuration>
And here is an example of how it works.
No comments:
Post a Comment