Creating shared blocks programmatically (MVC)

Vote:
 

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

#74629
Sep 03, 2013 10:05
Vote:
 

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

    

#74630
Sep 03, 2013 10:37
Vote:
 

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

#138975
Sep 24, 2015 13:33
Vote:
 

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.

#139230
Sep 28, 2015 8:17
Vote:
 

Got it to work! The shared block is created exactly the way of the previous post of Valdis!

#139248
Sep 28, 2015 12:31
This thread is locked and should be used for reference only. Please use the Episerver CMS 7 and earlier versions forum to open new discussions.
* 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.