Wednesday, December 10, 2014

Global DataSource Base Class for Sitecore Controls

One of the things I started to do in Sitecore development is to utilize a common base class for all .ascx's that utilize a "global data source".  By global data source, I'm talking about data that lives outside of the page template.  This has many uses, such as when you have content that should be common across pages (header / footer maybe?), or any controls that display one-to-many relationship type data.

public class BaseGlobalDataControl : System.Web.UI.UserControl
{
        private Item _dataSource;
        public Item DataSource
        {
            get
            {
                if (_dataSource == null)
                {
                    var parent = Parent as Sublayout;
                    if (parent != null)
                        _dataSource = Sitecore.Context.Database.GetItem(parent.DataSource);
                }

                return _dataSource;
            }
        }
 }

Then on my child ascx's, the DataSource is used as the main data item that drives the control.  Very useful, and a very simple way to use inheritance in Sitecore development.

Media Items in Repeater

It's been a while since I've posted, but as I've been doing a lot of Sitecore work lately, here's a quick snippet of code I used to repeat a bunch of images directly from a media library folder.

<asp:Repeater runat="server" ID="rptPartners">
        <ItemTemplate>
            <li>
                <img src='<%# Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl((Sitecore.Data.Items.Item)Container.DataItem)) %>' />
            </li>        
        </ItemTemplate>
    </asp:Repeater>

This little snippet is useful when a collection of images come directly from a folder within the media library. Here's the backend code:

var imagesFolder = Sitecore.Context.Database.GetItem(Sitecore.Context.Item.Fields["FIELD NAME"].Value);
rptPartners.DataSource = imagesFolder.Children;
rptPartners.DataBind();

I realize to some Sitecore purists out there, it's somewhat heretical to be mixing repeaters with Sitecore code, but coming from an ASP.NET developer's standpoint, I've found that a lot of ASP.NET / Sitecore hybrid solutions tend to be the quickest ways to get what I need DONE.  Hopefully this will be useful for someone out there!