Friday, May 16, 2014

Obtain Sitecore Context Item From Custom Control Field

Let's say you are not satisfied with the out-of-the-box Image field control or you just want to build a totally new cool custom field.  You would do this by inheriting from either an existing field or from the Sitecore.Web.UI.HtmlControls class.

public class Image : Sitecore.Shell.Applications.ContentEditor.Image
{ ... }

Since this is a field control, there is no Execute method like a Command that accepts a CommandContext input parameter, how do we extract the context item that contains the current field we are looking at?

You can try calling the base method GetItem() but this returns the Content Editor item and is not what you want.  You can use Intellisense to bring up a whole bunch of other base methods that has the word "Item" in the name but none of those help.  They either return the Content Editor item or the field control as an item but not exactly the context item that contains the current field you are looking at.

Fortunately there is Viewstate information.  This information is only available when you dig deeper into the base class Sitecore.Web.UI.HtmlControls.  If you inspect this class via a decompiler like dotPeek, you can see extensive references to the GetViewStateString or GetViewStateBool methods.  These methods obtain values saved as key/value pairs that are part of the Viewstate information.  The key that we are concerned with in this scenario is "ItemId".

Simply put, to obtain the context item id, we have to put this property in our custom field control class:

public string ItemID
{
            get
            {
                return base.GetViewStateString("ItemID");
            }
            set
            {
                Assert.ArgumentNotNullOrEmpty(value, "value");
                base.SetViewStateString("ItemID", value);
            }
}

Then, to resolve the actual Sitecore item, you can call something like:

Sitecore.Data.Database.GetDatabase("master").GetItem(ItemID)
 
 

No comments:

Post a Comment