blog
Ensuring Valid Item Names When Programmatically Creating Items
Using the ItemUtil.ProposeValidItemName() Method

Here is today's Sitecore Tip of the Day: whenever you create a new item in Sitecore from C# code you should be sure to use the ItemUtil.ProposeValidItemName() method. This will ensure that the item name you are using is valid and will prevent Sitecore from throwing an Invalid Item Name Exception. Your call should look something like the below:

//...

var parentItem = Sitecore.Context.Database.GetItem("{D220E537-28C2-4A10-A4B9-27BB700CB3CD}");
var itemTemplate = Sitecore.Context.Database.GetTemplate(new ID("{D4515921-9B4E-4E6C-AF8A-FE6340D3F76C}"));

var proposedName = "some name (foo bar)";
var validName = ItemUtil.ProposeValidItemName(proposedName); //becomes "some name foo bar"

var item = parentItem.Add(validName, itemTemplate);

//...

Note that the ItemUtil.ProposeValidItemName() method uses the InvalidItemNameChars config setting, so any customizations that you make or additional characters that you choose to exclude will be accounted for. For example:

//...assuming that dashes are set to be invalid in item names...

var proposedName = "some-name";
var validName = ItemUtil.ProposeValidItemName(proposedName); //becomes "some name"

//...
0 Comments
Post a Comment