Automatically Insert Child Item On Item Create

A common design pattern for Sitecore implementations requires the insertion of a child item that represents a page resource folder. The insertion of such an item can be accomplished multiple ways. This post will cover some of the common approaches to inserting child items on item creation.

Branch Templates

Branch Templates allow you to easily insert multiple templates into the tree with a single insertion. Branch templates are extremely useful for allowing your content authors to create complex hierarchies with a single insertion. When the need arises to insert multiple items or one off situations that require a sub item Branch Templates are an effective choice. However, for our use case we want to insert a single item under all of our items that represent pages. If we used branch templates to accomplish this, we would have to create a unique branch template for each of our page templates.
Branch Template

  1. The Branch Template item
  2. The item that will be inserted into the tree, the $name token will ensure that the name entered by the content author upon creation will become the display name of the item.
  3. The child resource folder that will be inserted beneath the generic page item.

Event Handler

Another approach to handling this is via an event handler. Using an event handler allows us to extend the behavior of the item:added event. The item:created event can also be used as well, however it is important to understand the difference between the item:added and item:created events.

Rules Engine

The Rules Engine can also be used to automatically create child items. By creating custom conditions and actions we can leverage the default Item Saved Rule set. The draw back of this is that the rule will run every time the item is saved. This is problematic from a number of perspectives:

  • This rule is run on every item save.
  • If a content author wanted to delete a pages resources folder it would be recreated the next time the item was saved.
  • By allowing admins or developers to define custom rules that create new items, you risk introducing the possibility of creating infinite loops by a malformed rule.

While the default rules engine doesn't provide us with the facilities we need to handle this scenario safely, we can extend the rules engine with some simple logic to create an elegant solution to this problem.

Example of Custom Rule

The below custom rule is leveraging the Item Added event. I have also created a custom condition to check the template inheritance to ensure that it has a base template of Base Page and that it is a descendant of our sites Home node. It then inserts an item of a template type.
Item Added Rule