问题
I want to create a field that generates a running number. This number will be automatically generated everytime I create a new item and has to be unique.
Any examples of how this could be implemented? I don't want to use the Sitecore item ID for this.
回答1:
You can implement a custom token and just use your field. I think this is going to be the cleanest solution for your problem. You can add your custom algorithm to guarantee that the IDs are unique or you can just use Guid.NewGuid()
. You can check how to create custom tokens in this blog post.
回答2:
Alright. I came up with a solution inspired by the nsgocev blogpost. Our IDs needed to be stored somewhere, so I created an item inside the /sitecore/content/ that stores the last ID as a string. Set the start as "AA000000". Our Ids has a prefix of "AA" and 6 digits.
This is the logic that counts:
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
We also need to add our class to the web config file. Patch given class in:
<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>
Now when we create a new item with token "$articleid", the ID is AA000001. The next one will be AA000002 and so on.
Thank you @nsgocev for resource and answer.
来源:https://stackoverflow.com/questions/25644786/sitecore-custom-field-add-unique-value-on-create