This article will address the following issue when creating item.
Lets assume that your solution has some sort of document item. In that document item you have a Title field and a Navigation Title field. In the standard values of these field you have set $name, so that when a new item is created the name of the item is inserted into the Title and Navigation Title fields.
The problem is that there is limitations on item names. So if the editor wants a title that uses non english letters or an ambersand, the editor will have to edit the Title and Navigation Title field after the item has been created.
So what we accomplish in this article is that users can use the title of the item when creating it, the correct title is then inserted into the Title and Navigation Title fields, and afterwards our code changes the item name into a legal name.
There is three steps in this solution:
- Making a ItemEventHandler class
- Inserting the new class in the web.config
- Allowing the characters in the web.config
Make the new class
First we need to create a new class to handle the renaming of the item when it is created.
In this class we create the following method:
protected void OnItemAdded(object sender, EventArgs args)
{
if (args != null)
{
Item item = Event.ExtractParameter(args, 0) as Item;
if (item == null)
return;
string name = item.Name;
name = name.Replace("&", "And");
name = MakeCamelCase(name);
item.Editing.BeginEdit();
item.Name = name;
item.Editing.EndEdit();
}
}
As you can see this code replaces replaces spaces in the name, so the name is camel cased. It also replaces ambersands with the word and.
Inserting the new class in the web.config
In the web.config file insert the following line in the item:added event under configuration/sitecore/events
<handler type="[Namespace].[Class], [Name of dll]" method="OnItemAdded"/>
Now our code will be called every time a new item is created.
Allowing the characters in the web.config
Sitecore will not allow us to use ampersands in item names and will instead give an error. Therefore we have to change the regular expression in the ItemNameValidation setting to allow the use of ampersands in item names. This is done like this:
<setting name="ItemNameValidation" value="^[\w\*\$&][\w\s\-\$&]*$"/>
So now Sitecore allows us to create items with ampersands in their names.
Result
After these three steps the editors will be able to use the titles like ”Lyhne & Son” when creating an item. This text will be inserted into the Title and Navigation Title fields and the name of the item will be LyhneAndSon.
That is all for now. Happy coding.