Try our conversational search powered by Generative AI!

Get All Blocks By Block Type

Vote:
 

Hi All,

Through EPiserver API is it possible to get all blocks by its type ?

#142960
Jan 07, 2016 11:01
Vote:
 

Hope this helps:

var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var contentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();

var contentType = contentTypeRepository.Load<MyBlock>();
var contentUsages = contentModelUsage.ListContentOfContentType(contentType);

foreach (var contentUsage in contentUsages)
{
    // ...
}



#142962
Jan 07, 2016 11:49
Vote:
 

Hi Dejan,

Thank you for the example code. I have tried this, but its look like contentUsages contains lot of duplicate items(versions). How to filter or get actual content without version or published version ?

#143018
Jan 08, 2016 19:17
Vote:
 

Hi Venkatraman,

There was a onlyPublished flag in EPiServer CMS 7, but not anymore: http://world.episerver.com/documentation/class-library/?documentId=cms/7/f9fa26cc-ab72-084d-893e-35e300c870e6

Here's the modified code. Hope this helps :)

var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var contentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();

// get all usages of MyBlock, including versions
var contentType = contentTypeRepository.Load<MyBlock>();
var contentUsages = contentModelUsage.ListContentOfContentType(contentType);

// get distinct content references without version
var contentReferences = contentUsages
    .Select(x => x.ContentLink.ToReferenceWithoutVersion())
    .Distinct()
    .ToList();

// fetch data from DB
var instances = contentReferences
    .Select(contentReference => contentLoader.Get<IContent>(contentReference))
    .ToList();

// remove unpublished
new FilterPublished().Filter(instances);
#143037
Jan 11, 2016 10:10
* 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.