How to Create a Custom Field in Sitecore

May 1, 2014

Blog | Technology | How to Create a Custom Field in Sitecore
How to Create a Custom Field in Sitecore

Sitecore is a Content Management System (CMS) that allows the user to customize a webpage without writing a lot of HTML. This post isn’t meant to teach you Sitecore, but it will help you better understand how to create a custom field within its structure. I created this custom field in Sitecore while on Co-Op at GeekHive, this exercise taught me valuable information about how Sitecore works “under the hood.”

This post will demonstrate how you create an HTML input element of type range inside of Sitecore.

STEP 1:

Start off in the Core Database of the Sitecore shell and go to the Content Editor. Inside of the Content Editor navigate to Sitecore/System/Field Types and create a new folder called “Custom Field Types.”

CreateFolderInsideOfFieldTypes_Core

From there you can create a new Template Field Type. Right click, Insert From Template/System/Templates/Template Field Type and name it “Range Field.”

 

 

AddTemplateIntoCreatedFolder_AddControlName_Core

 

 

Inside of your newly created template go to the text box labeled Control and give it a value of “myfields:RangeFieldControl.” This comes into play a little later on, so don’t forget what you named it.

STEP 2:

Swap over to the Master Database and add this field to a template. Go into the Content Editor and under Templates choose New Template.

In the text box labeled “Add a new section”, give it a value of “Data”, then add in a new field and call that “Range.” Under the drop down, give that a value of the field you just created in the core database which in your case would be “Range Field.”

Then, in the source section, place in a query string for the min., max., and step attributes. If you don’t know what query strings are or you need a fresh touch up, take a look at this blog post from zzzzBov.

STEP 3:

Set up the C# class for your custom template:

Start up your favorite version of Visual Studio. From the startup screen go to File/New Project/Visual C#/Web/ASP.NET Web Forms Application and name it “CustomFieldTest.Web.” Right click the project name in the Solution Explorer and select add/class, make sure that you’re still under Visual C#, and that the class item is selected. Name this class the same thing as your template field control. Remember when I said don’t forget what you named it? The name of the class should match whatever the name you put after the “myfields:”, in this example it was “myfields:RangeFieldControl.”

STEP 4:

Before you can make your element you have to map the field prefix to an assembly and namespace. This is achieved by going into your web.config file , searching for “controlSources” and adding this line:


This tells Sitecore that any control identified using the prefix “myfields” can be located in the “CustomFieldTest.Web” assembly and is a part of the “CustomFieldTest.Web” namespace.

Now it is time to start creating the item.

STEP 5:

From inside of the class you just created make sure you update your using statements to the following:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.HtmlControls;
using Sitecore;
using Sitecore.Diagnostics;
using Control = Sitecore.Web.UI.HtmlControls.Control;

Also, make sure this class extends from “Sitecore.Web.UI.HtmlControls.Control.”

STEP 6:

Create properties for the field you just created:

public string Source
{
    get { return StringUtil.GetString(ViewState["Source"]); }
    set
    {
        Assert.ArgumentNotNull(value, "value");
        ViewState["Source"] = value;
    }
}

public string InputId
{
    get { return GetID("input"); }
}

public string TextMinId
{
    get { return GetID("textMin"); }
}

public string TextMaxId
{
    get { return GetID("textMax"); }
}

The source property here will grab the source from the query string that you passed into your source attribute when you created the custom field – the query string. The other properties are there to represent the ID’s of the HTML elements so you don’t have to keep writing them over and over and they also makes the code look cleaner.

STEP 7:

Override the OnLoad method, a method that belongs to Control:

   protected override void OnLoad(EventArgs e)
    {
        if (!Sitecore.Context.ClientPage.IsEvent)
        {
            var sourceVals = HttpUtility.ParseQueryString(Source);

            var wrapper = new HtmlGenericControl { TagName = "div" };
            wrapper.Attributes["class"] = "wrapper";

            var textMin = new HtmlGenericControl
            {
                TagName = "span",
                InnerText = "Min: " + sourceVals["min"],
                ID = TextMinId
            };

            var input = new HtmlGenericControl
            {
                TagName = "input",
                ID = InputId
            };
            input.Attributes["type"] = "range";
            input.Attributes["min"] = sourceVals["min"];
            input.Attributes["max"] = sourceVals["max"];
            input.Attributes["step"] = sourceVals["step"];
            input.Attributes["value"] = Value;
            input.Attributes["name"] = InputId;
            input.Attributes["class"] = "slider";
            input.Attributes["style"] = "vertical-align:middle;";

            var textMax = new HtmlGenericControl
            {
                TagName = "span",
                InnerText = "Max: " + sourceVals["max"],
                ID = TextMaxId
            };

            wrapper.Controls.Add(textMin);
            wrapper.Controls.Add(input);
            wrapper.Controls.Add(textMax);

            Controls.Add(wrapper);
        }
        else
        {

        }
        base.OnLoad(e);
    }

This method will check if the control you’re trying to create has been loaded in already. This is done when you check to see if the ClientPage is in a postback. If the “ClientPage.IsEvent” is false then most likely the item has not been created yet, and you’d need to create it. Then, you can go into Sitecore to check out your pretty range field that displays your min. and max. values with a cool slide bar.

STEP 8:

You may have noticed that when you try to update this field and save it the value is not retained. Here’s where you’re going to resolve that.

 protected override void OnLoad(EventArgs e)
        {
            if (!Sitecore.Context.ClientPage.IsEvent)
            {
                Build();
            }
            else
            {
                var value = Context.Request.Form[InputId] ?? "";
                Sitecore.Context.ClientPage.Modified = Value != value;

                if (value != null && value != Value)
                    Value = value;
            }
            base.OnLoad(e);
        }
        

This code will run when the “ClientPage.IsEvent” returns true. An important example of when this code will run is when an item is saved inside of the current web forms page.

That’s it, you’re done! Now you know how to create a custom Sitecore field, and you can go and add this to an HTML page and style it however you want. You may also want to add more to the backend code to check if the values passed into the query string were actual numbers and if they accidentally swapped the min. and max. values and so on. You decide.

A good thing to keep in mind is that when you render this to a page, you’re never going to see the slide bar. It will only display a text value which would be the value attribute of the input element. To display an actual range input you need to create it on your page with the appropriate attributes.

Nate Kierpiec

Developer
Tags
  • Custom Field
  • Sitecore
subscribe to GeekHive's newsletter

Never miss out on a Sitecore update again!

Our newsletter features a blog roundup of our top posts so you can stay up to date with industry trends, tutorials, and best practices.

Recent Work

Check out what else we've been working on