Quantcast
Channel: Sitefinity – Falafel Software Blog
Viewing all articles
Browse latest Browse all 73

Get Images from Custom Field in One Query – Sitefinity

$
0
0

Consider a situation where we have a custom image field (let’s call it ImageGallery) and we would want to get all images from all items of the module. Let’s take an example of the News module with the image field allowing to select multiple images.

public IQueryable<Image> GetAllImages(int count = 0)
{
    string fieldName = "ImageGallery";
    string parentItemTypeName = typeof(NewsItem).FullName;
    var librariesManager = Telerik.Sitefinity.Modules.Libraries.LibrariesManager.GetManager();
    var contentLinksManager = Telerik.Sitefinity.Data.ContentLinks.ContentLinksManager.GetManager();

    var parentItems = GetAll();
    var parentItemIds = parentItems.Select(i => i.OriginalContentId).ToList();

    var allImages = librariesManager.GetImages().Where(i => i.Status == ContentLifecycleStatus.Live && i.Visible);

    var contentLinks = contentLinksManager.GetContentLinks().Where(cl => cl.ParentItemType == parentItemTypeName && cl.ComponentPropertyName == fieldName && parentItemIds.Contains(cl.ParentItemId));

    var relatedImages = contentLinks.Join<Telerik.Sitefinity.Model.ContentLinks.ContentLink, Image, Guid, Image>(
        allImages, 
        (cl) => cl.ChildItemId, 
        (i) => i.OriginalContentId, 
        (cl, i) => i
        );

    if (count > 0)
    {
        relatedImages = relatedImages.Take(count);
    }

    return relatedImages();
}

public IQueryable<NewsItem> GetAll()
{
    var manager = Telerik.Sitefinity.Modules.News.NewsManager.GetManager();
    var items = manager.GetNewsItems().Where(i => i.Status == ContentLifecycleStatus.Live && i.Visible);

    return items;
}

Happy coding! Register now for FalafelCon 2014 and perfect your skills, expand your horizons, and get inspired.

The post Get Images from Custom Field in One Query – Sitefinity appeared first on Falafel Software Blog.


Viewing all articles
Browse latest Browse all 73

Trending Articles