Sitecore-自定义字段,在创建时添加唯一值
本文关键字:添加 唯一 创建 自定义 字段 Sitecore- | 更新日期: 2023-09-27 18:20:40
我想创建一个生成连续数字的字段。每次我创建新项目时,这个数字都会自动生成,并且必须是唯一的。
关于如何实现这一点,有什么例子吗?我不想为此使用Sitecore项目ID。
您可以实现一个自定义令牌,只需使用您的字段。我认为这将是解决你的问题最干净的方法。您可以添加自定义算法以确保ID是唯一的,也可以只使用Guid.NewGuid()
。你可以在这篇博客文章中查看如何创建自定义令牌。
好的。受nsgocev博客文章的启发,我想出了一个解决方案。我们的ID需要存储在某个地方,所以我在/sitecore/content/中创建了一个项目,将最后一个ID存储为字符串。将起始设置为"AA000000"。我们的ID有一个前缀"AA"和6位数字。
这就是重要的逻辑:
Namespace Tokens
Public Class GeneratedArticleId
Inherits ExpandInitialFieldValueProcessor
Public Overrides Sub Process(ByVal args As ExpandInitialFieldValueArgs)
If args.SourceField.Value.Contains("$articleid") Then
Dim database = Sitecore.Client.ContentDatabase
Dim counter = database.GetItem(New ID("Our Item"))
If counter Is Nothing Then
args.Result = ""
Exit Sub
End If
Dim idfield = AppendToIdValue(counter("ID"))
Using New SecurityDisabler()
counter.Editing.BeginEdit()
counter.Fields("ID").Value = idfield
counter.Editing.EndEdit()
End Using
If args.TargetItem IsNot Nothing Then
args.Result = args.Result.Replace("$articleid", idfield)
End If
End If
End Sub
'Extracts the digits and adds one
Private Shared Function AppendToIdValue(ByVal id As String)
Dim letterprefix = Left(id, 2)
Dim integervalue = CInt(id.Replace(letterprefix, ""))
integervalue += 1
Return letterprefix & integervalue.ToString("000000")
End Function
End Class
End Namespace
我们还需要将我们的类添加到web配置文件中。修补程序中给定的类:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<expandInitialFieldValue help="Processors should derive from Sitecore.Pipelines.ExpandInitialFieldValue.ExpandInitialFieldValueProcessor">
<processor patch:after="*[@type='Sitecore.Pipelines.ExpandInitialFieldValue.ReplaceVariables, Sitecore.Kernel']" type="OurLibrary.Tokens.GeneratedArticleId, OurLibrary"/>
</expandInitialFieldValue>
</pipelines>
</sitecore>
</configuration>
现在,当我们使用令牌"$articleid"创建一个新项目时,ID为AA000001。下一个将是AA000002,依此类推。
感谢@nsgocev提供的资源和答案。