Knowledge Base

Working With Custom Hooks: OnNew

Become familiar with one of the most commonly used custom hooks in the system. The OnNew custom hook is fired when a new item is created in the Site Tree.


The OnNew custom hook is fired when a new item is created in the Site Tree. It is one of the most used custom hooks in the system because, often, new content coming into the tree necessitates subsequent actions. When setting up this custom hook, you are given the new object that was created and the session that created it as parameters to work within.

OnNew Custom Hook Example

Considerations

Be careful when using this hook to create new content in the site tree as it’s easy to make an infinite loop when the new item created by the hook calls the OnNew hook again. Make sure you have good termination conditions for your hooks and conditionals to prevent them firing when not needed.

Examples

The first example is extremely straight forward: if there is a title element on the page (not component), and the value isn’t already set, fill the title element in with the same value as the name of the page that was entered during creation. This script is helpful because often the name of the page in the site tree and the name in the title element are the same. So, you save users time by not having to enter the title into each place.  

if(!page.IsComponent)

{

     IElement title = page.Element("Title");

     if(title != null && title.Value == "")

     {

          title.Value = page.Name;

     }

}

In the second example below, the script creates a folder under an index page type to store the items that will be indexed by the page. Users in the site needed to create this folder anyway as their next step, so this cuts to the chase and it’s done it for them.

This could be taken even further by understanding the full process a user would go through after creating a folder and hook in more predictive actions, such as setting a navigation on the page to start at that folder or checking in finished items (like the folder) to the correct publishing targets automatically.

if(page.SchemaName == "IndexPage")

{

     ISchema folder = session.SchemasManager.SchemaByRootName("Folder");

     IContentItem newFolder = page.CreateChildPage(page.Name + " Items", folder, true);

     newFolder.Save();

}                   

  • PRODUCT: CMS
  • VERSION: CMS 10
  • RELEASE: 10.x
  • Published: May 30, 2022
  • LAST UPDATED: September 18, 2023
  • Comments: 0

Please login to comment

Comments


There are no comments yet.