Inserting of new child document in OnAfterInsert method of Custom Tree node handler
It seems there is no new child document in the content tree which should be created by API in OnAfterInsert method of CustomTreeNodeHandler. However, the new document is listed in List view and saved in database. Why it happens?
This article will explain you why the node is not in the content tree and advice how you may make it appear. We will use a sample that we want to create a new Folder document if the document of custom type is created in CMSDesk.
We use the CustomTreeNodeHandler and insert the following code into OnAfterInsert method:
publicoverridevoid OnAfterInsert(object treeNodeObj, int parentNodeId, object tree)
{
CMS.TreeEngine.TreeNode tnNode = (CMS.TreeEngine.TreeNode)treeNodeObj;
TreeProvider treeProvider = (TreeProvider)tree;
// based on the class name of the new node, check:
switch (tnNode.NodeClassName)
{
// if this is a custom document type page...
case"custom.documenttype":
// ...automatically create a new folder
CMS.TreeEngine.TreeNode nodeFolder = new CMS.TreeEngine.TreeNode("CMS.Folder", treeProvider);
nodeFolder.NodeName = "Features";
nodeFolder.NodeAlias = "Features";
nodeFolder.DocumentCulture = tnNode.DocumentCulture;
nodeFolder.Insert(tnNode.NodeID);
break;
}
}
Then test the behavior. Create a document called “Test” of custom document type in CMSDesk but the new folder does not appear in the content tree.
The problem is that when you access the
OnAfterSave method of
CustomTreeNodeHandler the object of “Test” document is already created in memory. If you add a new child it updates the number of children in database but it does not affect the current object of “Test” in memory. The object from memory re-writes the record in database just after it goes through the
CustomTreeNodeHandler. When the object is not updated the database record is incorrect. That is why we do not see the folder document underneath the “Test”.
Adding the following code to the switch statement updates the parent object:
case"custom.documenttype":
// ...automatically create a new folder
CMS.TreeEngine.TreeNode nodeFolder = new CMS.TreeEngine.TreeNode("CMS.Folder", treeProvider);
nodeFolder.NodeName = "Features";
nodeFolder.NodeAlias = "Features";
nodeFolder.DocumentCulture = tnNode.DocumentCulture;
nodeFolder.Insert(tnNode.NodeID);
//update the child nodes countof parent
tnNode.SetValue("NodeChildNodesCount",
tnNode.NodeChildNodesCount + 1);
tnNode.Update();
break;
See also: More information about
CustomTreeNodeHandler
API sample code of
node insertingApplies to: Kentico CMS 4.1