Here is the example of creating a shared block in the global block folder. I guess you can just replace global folder with yours.
var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var languageSelectorFactory = ServiceLocator.Current.GetInstance<LanguageSelectorFactory>();
var blockType = contentTypeRepository.Load<AwesomeBlock>();
var block = contentRepository.GetDefault<IContent>(ContentReference.GlobalBlockFolder, blockType.ID, languageSelectorFactory.Create(ContentLanguage.PreferredCulture.Name));
block.Name = "My new awesome block";
contentRepository.Save(block, SaveAction.Publish, AccessLevel.NoAccess);
Great,
Can I link a create Shared Block to a page on the PageCreated event? I see examples of local blocks, but how do i do this for a shared block, and how do i make sure that the shared block is created in the right folder connected to the page?
Thanks in advance,
Ron
You can place shared blocks on page's ContentArea.
var area = page.ContentArea.CreateWritableClone(); area.Items.Insert(0, new ContentAreaItem { ContentLink = blockLink }); page.ContentArea = area;
NB! Note last line - you need to "reassign" content area back the page's property in order to update the page properly.
I haven't tried this on PageCreated event, but don't see any limitations here that it would not be possible.
Shared blocks are living their own lifecycle in the folder you created them in. If you refer to assets folder "For this page only" - then it feels like local block folder where you can create block that can be used more than once on the page. Blocks created there are not accessible for other pages.
Got it to work! The shared block is created exactly the way of the previous post of Valdis!
I would like to create shared blocks programmatically, but only manage to make local blocks.
The usuan way repository.GetDefault<T>(parentPage) will only make it local.
I would like to create a shared Folder called "Praktisk" under Global folders, and then make a AwesomeBlock under the folder.
I've found code for making folders, but not adding the blocks to the folder