Creating a custom field is pretty simple. Let’s take the example of a simple email field. The field will store a single email. It will include a validation button for email validation as well. Other than that, it will function just like a regular text field.

Step 1: Create Visual Studio Project for the field

Simply create a project of the type Class Library.

Step 2: Implement a class for the field

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Sitecore.Shell.Applications.ContentEditor;

 

namespace XCore.SharedSource.ExampleFields

{

    public class EmailField : Edit

    {

        public EmailField()

        {

        }

    }

}

Let’s start by just creating the class, and inherit from the Edit control in Sitecore. This gives us a good starting point for our class. We’ll add functionality later.

Step 3: Add config file with field type

config file

Config File Added

Insert a custom configuration file (.config) in your App_Config/Include folder: Add the following (replace the Namespace/Assembly with your namespace/assembly of course):

<configuration xmlns:x="https://www.sitecore.com/xmlconfig/">

  <sitecore>

    <controlSources>

      <source mode="on" namespace="XCore.SharedSource.ExampleFields" assembly="XCore.SharedSource.ExampleFields" prefix="xcore" />

    </controlSources>

  </sitecore>

</configuration>

Notice: prefix=”your module/library prefix” will be used later to identify code for your control.

Step 4: Create new Field in the Sitecore Core Database

Switch to the core database

core database

switch to the core database

Once, in the core database, open the Content Editor.

content editor

Create the field, in this case under Simple Types

In the system section, you’ll find “Field Types” – this is where Sitecore stores the available field types. Create your own from the “Template field type” – or duplicate another field like the one you are creating. Specify the Control value – this is basically your prefix : your class name from the configuration file we create before.

Step 6: Configure Field context menus

Configure Field context menus

Create a regular folder called Menu for any context buttons for the Sitecore field

Step 7: Implementation

And now to the fun part. The code below is the full code for the email field.

We inherit from the Edit control as a base. We set the CSS class “scContentControl” on the field to align it with the design of text fields in Sitecore in general.

We implement / override the HandleMessage function – this function handles messages sent in Sitecore. If the message matches emailfield:validate as specified in the previous section, then we know our validate button was clicked.

We then call EmailValidate() to validate the email field text. This is done using WebUtil.GetFormValue(ID) – where ID is the current field ID of our Sitecore field.

Send data back to the Sitecore client is done using SheerResponse.SetInnerHtml which finds the validatortext HtmlGenericControl specified in RenderValidatorOutput – the function that adds the text control showing valid/invalid status to the end user.

 

using System;

using Sitecore.Web;

using Sitecore.Web.UI.Sheer;

using System.Web.UI.HtmlControls;

using Sitecore.Web.UI.HtmlControls;

using Sitecore;

using System.Text.RegularExpressions;

 

namespace XCore.SharedSource.ExampleFields

{

    public class EmailField : Edit

    {

        public EmailField()

        {

            this.Class = "scContentControl";

        }

 

        public override void HandleMessage(Message message)

        {

            base.HandleMessage(message);

 

            switch (message.Name)

            {

                case "emailfield:validate":

                    this.EmailValidate();

                    break;

            }

        }

 

        protected void EmailValidate()

        {

            string currentvalue = WebUtil.GetFormValue(ID);

            if (Regex.IsMatch(currentvalue, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))

                SheerResponse.SetInnerHtml("validator_" + ID, "Valid email entered!");

            else

                SheerResponse.SetInnerHtml("validator_" + ID, "Invalid");

        }

 

        protected override void OnPreRender(EventArgs e)

        {

            base.OnPreRender(e);

            this.ServerProperties["Value"] = this.ServerProperties["Value"];

        }

 

        protected override void Render(System.Web.UI.HtmlTextWriter output)

        {

            base.Render(output);

            RenderValidatorOutput(output);

        }

 

        protected void RenderValidatorOutput(System.Web.UI.HtmlTextWriter output)

        {

            HtmlGenericControl validatortext = new HtmlGenericControl("div");

 

            validatortext.Attributes.Add("ID", "validator_" + ID);

            validatortext.Attributes.Add("style", "color:grey");

            validatortext.InnerHtml = "";

 

            validatortext.RenderControl(output);

        }

 

        protected override bool LoadPostData(string value)

        {

            value = StringUtil.GetString(new string[1]

            {

                value

            });

 

            if (!(this.Value != value))

                return false;

 

            this.Value = value;

            base.SetModified();

 

            return true;

        }

    }

}

Compile the class, include it in your web project (copy the class libraries output dll to your website, or include the project in a joint solution)

Step 7: Add field with new field type on a template

Now we are ready to add the control to a template. For testing, we have created “MyTemplate” – and added a field “Dealer Email”. Since we added the field type in the Core database, it now is available to us in the template field drop down.

Add field with new field type on a template

Selected the new field type on your template

Now, let’s create an items based on the template, and verify our field renders:

an items based on the template

Create an instance of your Sitecore Template, make sure your field renders

The field appears as a standard Sitecore Text field, but includes the Validate Button.

validate button

Invalid email

The validation obviously fails. Let’s try with a regular email:

validate button

Valid email entered

And that concludes how simple it is to create a custom field in Sitecore. In later posts, we’ll go over more advanced fields.