Wednesday, December 16, 2015

EPiServer 7< - Programatically Create Pages with Blocks and Content Areas

Stuff we needed  before we get started:

  private static IContentRepository Repo  
     {  
       get  
       {  
         return ServiceLocator.Current.GetInstance<IContentRepository>();  
       }  
     }  

Create The page

 var DefaultPage= Repo.GetDefault<SOMEPAGETYPE>(SOMEPAGEREF, contentType.Load<SOMEPAGETYPE>().ID);  


Bind the properties you want added to you page.
Save the page (Needed because you cannot add blocks to a not saved page).


  var pageCopy= Repo.Save(DefaultPage, SaveAction.Publish, AccessLevel.NoAccess);  

To the pagecopy we need to find out the assetsFolder where we will add the blocks.


  var assetsFolder = ContentAssetHelper.GetOrCreateAssetFolder(pageCopy);  
  Repo.GetDefault<SomeBlock>(assetsFolder.ContentLink);  

Create block -  in assets folder then bind the data to the block and save it like this:


  Repo.Save(SomeBlock as IContent, SaveAction.Publish, AccessLevel.NoAccess);  

Then we need to get the created blocks from the assets folder and add them to ther contentArea. Something like this:


  foreach (var someBlockItem in Repo.GetChildren<SomeBlock>(assetsFolder.ContentLink))  
       {  
         var cAreaItem = new ContentAreaItem()  
         {  
           ContentLink = ((IContent)someBlockItem ).ContentLink  
         };  
         writableArea.Items.Add(cAreaItem);  
       }  
       pageCopy.SomeArea =  writableArea;   // (ContentArea Property)
      
       Repo.Save(pageCopy, SaveAction.Publish, AccessLevel.NoAccess);  

No comments:

Post a Comment