Monday, November 13, 2017

The Glass is Half Empty - Why can I not get all children of type Image from the media library folder?

So here is the problem.  I have a component where the user assigns a media folder for say a photo gallery.  Now I simply want to pull in all images from beneath this folder. I was tempted to do this but it always returns null.

imageFolderItem.Children.OfType<Image>()

But why?  Well according to Sitecore Poutine (Corey Smith AKA Sitecorey) the Image represents an Image field not the Sitecore Image template.  So to accomplish this you would simply do the following:

Go to the definition of Image and copy the class.  Make your own class but call it ImageItem.
Now set the TemplateId to be the Id of the Image template in Sitecore.

    /// <summary>
    /// This is an item based on the image template. If you are after the field use Image.
    /// </summary>
    [SitecoreType(TemplateId = "{F1828A2C-7E5D-4BBD-98CA-320474871548}", AutoMap = true)]
    public class ImageItem : IgnitionViewModel
    {
        //
        // Summary:
        //     Gets or sets the alt.
        public string Alt { get; set; }
        //
        // Summary:
        //     Gets or sets the border.
        public string Border { get; set; }
        //
        // Summary:
        //     Gets or sets the class.
        public string Class { get; set; }
        //
        // Summary:
        //     Gets or sets the height.
        public int Height { get; set; }
        //
        // Summary:
        //     Gets or sets the H space.
        public int HSpace { get; set; }
        //
        // Summary:
        //     Gets the SRC.
        public string Src { get; set; }
        //
        // Summary:
        //     Gets or sets the V space.
        public int VSpace { get; set; }
        //
        // Summary:
        //     Gets or sets the width.
        public int Width { get; set; }
        //
        // Summary:
        //     Gets or sets the media id.
        public Guid MediaId { get; set; }
        //
        // Summary:
        //     Gets or sets the title.
        public string Title { get; set; }
        public Language Language { get; set; }
    }

Now your call can look like this:

     imageFolderItem.Children.OfType<ImageItem>());

And my Symposium 2017 Selfie pictures are returning.













I wish I had found this article a couple hours ago so if you have written one on this issue and have a better description on what the issue is and how to solve it comment here.  Hopefully this will help someone else with the issue.

No comments:

Post a Comment