In sitecore, let's say I have an Item parentItem
under it I want to create an item childItem
which is based on Template templateItem
, only when the childItem
does not exist.
So the following code should only execute if the item not exist as child already.
parentItem.Add("Child Item", templateItem);
What do you mean saying item exists? Item with the same name? In Sitecore it is possible to have multiple items with the same item name. Those items in fact are not the same and have different IDs.
So in order to avoid creating another child item of the same template with the same name under the same parent, you need to upgrade your construction to the following:
string itemName = "Child item";
if(!dataItem.Children.Any(i=>i.Name == itemName && i.TemplateID == templateItem.ID))
{
dataItem.Add(itemName, templateItem);
}
Of course, it is not a good idea to have that clause from above everywhere, so you might want to automate that on every item creation. In order to do that, create your custom item:creating event handler with your custom one, like that:
<event name="item:creating">
<handler type="Your.Type, Your.Assembly.Name" method="OnItemCreating" />
And within OnItemCreating method, implement the same snippet from above.
Hope this helps!