EPiServer: Auto-create child pages on ‘Add New Page’

I spent almost a day trying to figure this out. I’ve seen heaps of examples on the internet on how to programmatically create pages in EPiServer, but it was a struggle finding a resource that explained where we can do this. Or where we can insert such code. When I finally found a solution, I felt proud. And happy. And this lead me to creating a new blog. Yay for my very first post!

Problem: On add of a new page via the EPiServer Edit page, the system should determine if the page type selected requires children to be created automatically under it.

Solution: We need two things: A new Attribute that can be attached to page types. And a class of the IInitializableModule (EPiServer.Framework) which intercepts creation of pages, checking if the page type has this new Attribute. If it does, it will call a method that will create children under it.

Sounds simple right? But I was new to EPiServer, still am actually. So I thought of creating a blog where I can write about my journeys in EPiServer hoping that someday these struggles I have and the ones I will be going through can be avoided in the future by someone like you who happens to have found my page.

So here’s how my Attribute class looks like

 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]  
 public class EnsureSubPageAttribute : Attribute  
     public Type PageType { get; set; }    
     public string PageName { get; set; }    
     public string UrlSegment { get; set; }    
     public int SortIndex { get; set; }    
     public string SetReferenceToProperty { get; set; }    
     public string[] SetPropertyNames { get; set; }    
     public string[] SetPropertyValues { get; set; }  

And then create a Class that goes by the interface IInitializableModule.
Implement members by attaching an event handler when a page is created.

 public class EnsureSubPages : IInitializableModule  
     #region IInitializableModule Members  
     public void Initialize(InitializationEngine context)  
       DataFactory.Instance.CreatedPage += Instance_CreatedPage;   
     public void Uninitialize(InitializationEngine context)  
       DataFactory.Instance.CreatedPage -= Instance_CreatedPage;  

Then of course, implement the event handler method.

Once this is implemented, we go ahead and attach the attribute to the appropriate page types.
Here’s an example:

     PageType = typeof(ChildPage),  
     UrlSegment = "give-it-a-url")]  
 public class AutoParentPage : SitePageData  

Any questions, just comment! Thanks

%d bloggers like this: