Try our conversational search powered by Generative AI!

Adding blocks to a page programmatically?


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.
Oct 08, 2014 15:22
var rep = ServiceLocator.Current.GetInstance();
var newBlock = rep.GetDefault();
newBlock.YouProp = "Cool stuff";
rep.Save((IContent)newBlock, SaveAction.Publish)

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

Oct 08, 2014 17:05

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

Oct 09, 2014 12:13
            clone.MainContentArea.Items.Add(new ContentAreaItem()
                ContentLink = myReference

Oct 09, 2014 12:46

There is a forum post with similar code that you could use:

Oct 09, 2014 12:54

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 = "";
                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;

                rep.Save(writableClonePage, SaveAction.Publish, AccessLevel.NoAccess);
Oct 09, 2014 13:11


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);
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.