Is there way in sitecore to ensure that a certain type of item can only have 1 child of a certain type of item? I\'m reading the rules engine cookbook, but I\'m not getting much
One of the sites I worked on had a requirement that no more than 6 child items could exist below a certain item type. We considered using an insert option rule, but decided to abandon the idea because it did not prevent copying, moving, or duplicating items.
Instead we decided to extend the item:created
event with a handler specifically for this task. Below is a stripped-down example of how it works. One obvious improvement would be to fetch the maximum child limit from a field on the parent item (visible to administrators only, of course). You could probably even leverage the rules engine here as well...
public void OnItemCreated(object sender, EventArgs args)
{
var createdArgs = Event.ExtractParameter(args, 0) as ItemCreatedEventArgs;
Sitecore.Diagnostics.Assert.IsNotNull(createdArgs, "args");
if (createdArgs != null)
{
Sitecore.Diagnostics.Assert.IsNotNull(createdArgs.Item, "item");
if (createdArgs.Item != null)
{
var item = createdArgs.Item;
// NOTE: you may want to do additional tests here to ensure that the item
// descends from /sitecore/content/home
if (item.Parent != null &&
item.Parent.TemplateName == "Your Template" &&
item.Parent.Children.Count() > 6)
{
// Delete the item, warn user
SheerResponse.Alert(
String.Format("Sorry, you cannot add more than 6 items to {0}.",
item.Parent.Name), new string[0]);
item.Delete();
}
}
}
}