Adding blocks to a page programmatically?

Vote:
 

Is it possible to programmatically add blocks to a page?

I would assume that you would have to to something like this

  • make a writabel clone of the page
  • create an instance of a block
  • add content to the block (set property values)
  • add the block to the page/clones content area
  • save/publish the page/clone.
#91552
Oct 08, 2014 15:22
Vote:
 
var rep = ServiceLocator.Current.GetInstance();
var newBlock = rep.GetDefault();
newBlock.YouProp = "Cool stuff";
rep.Save((IContent)newBlock, SaveAction.Publish)
writableClonePage.ContentArea.Items.Add(newBlock)

Just writing from memory here so could be a bug or two in there. But something like it. =)

#91566
Oct 08, 2014 17:05
Vote:
 

Thanks Petter. But it seems ContentArea.Items.Add() expects a ContentAreaItem object?

#91605
Oct 09, 2014 12:13
Vote:
 
            clone.MainContentArea.Items.Add(new ContentAreaItem()
            {
                ContentLink = myReference
            });



#91607
Oct 09, 2014 12:46
Vote:
 

There is a forum post with similar code that you could use: http://world.episerver.com/Modules/Forum/Pages/Thread.aspx?id=86474

#91608
Oct 09, 2014 12:54
Vote:
 

Thanks a bunch!

Here's what I ended up with:

                var writableClonePage = (LandingPage)CurrentPage.CreateWritableClone();
                var rep = ServiceLocator.Current.GetInstance();

                var newBlock = rep.GetDefault(ContentReference.GlobalBlockFolder);
                newBlock.ButtonLink = "http://www.episerver.no";
                newBlock.ButtonText = "My button text";
                IContent icontentBlock = (IContent)newBlock;
                icontentBlock.Name = "Some name";
                var savedReference = rep.Save(icontentBlock, SaveAction.Publish, AccessLevel.NoAccess);

                var myContentAreaItem = new ContentAreaItem();
                myContentAreaItem.ContentLink = savedReference;

                writableClonePage.MainContentArea.Items.Add(myContentAreaItem);
                rep.Save(writableClonePage, SaveAction.Publish, AccessLevel.NoAccess);
#91610
Oct 09, 2014 13:11
Vote:
 

NP.

In case you would rather use the "for this page" folder, you could simply add:

                var contentAssetHelper = ServiceLocator.Current.GetInstance();
                ContentAssetFolder folder = contentAssetHelper.GetOrCreateAssetFolder(myPage.ContentLink);
                var newBlock = contentRepository.GetDefault(folder.ContentLink);
#91612
Oct 09, 2014 13:18
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.