Stepping through the Sitecore Forms - Walkthrough: Creating a Custom Form Element
Jeremy Streeter
Senior Technology Leader | MS in Software Engineering | Empathetic | Heuristic | People Focused
I recently invested a good amount of time into following the walkthrough for creating Custom Form Elements for the new Sitecore 9 Experience Forms, found here: https://doc.sitecore.com/developers/90/sitecore-experience-management/en/walkthrough--creating-a-custom-form-element.html.
So I decided to write about it...
Introduction
This work was done using Sitecore 9.0.1 build 171219. Leveraging Microsoft Visual Studio, Git for Source Control, and Unicorn for Serialization.
Though I did not follow the walkthrough exactly, you may find reading this along with the walkthrough from Sitecore will help you save some time and troubleshooting as you create your own custom Sitecore Form Element. For my needs, I was making a Checkbox form element that supports a Rich Text label. This attempt in creating a custom Sitecore Form Element was a success.
From the beginning to the end of the walkthrough provided by Sitecore, this guide should help fill in some details and emphasize some steps that need your attention. A lot of this guide is developed from my personal experience of following the walkthrough and occasionally troubleshooting to eventually arrive at the goal of making a Custom Sitecore Element.
Before continuing, I want to thank Scott Gillis (Sitecore MVP) for his assistance in unraveling some of the hurdles I faced along the way, and are now detailed below.
Let's get started...
Step 1: Create a Field Template
In Step 1.1 "In the Sitecore Content Editor, navigate to sitecore/Templates and create a new folder. For example, the Fields folder." Do not do this!
You should create your template in this exact path to save time and energy later: sitecore/Templates/System/Forms/Fields
Why? This specific location in the Sitecore Templates is directly referenced as a datasource for a field, (that you select using a dropdown), in the Field Type Item you create in the last step of the walkthrough.
For my purposes, I only created a Rich Text field, that I just decided to call RichText.
Do not forget to:
- Click the Shared check box for every field you add.
- Add Standard Values to your Field Template.
If you forget either of these things, you will get to see your editor on the right, drag it over, see the animation spin, and then it will not error. If you get to that point, get no error, and see nothing in the logs about the forms, you probably forgot one of these two things.
Also, look at the Content tab for your newly created Field Template. Click around to the Content tabs of other Field Templates, and you will soon discover that they're using a series of base templates. This is a good opportunity to wash, rinse, and repeat (and copy good structure habits). If you are wondering where all those Settings Templates are, just scroll down in the tree a little. They are all under /Sitecore/Templates/System/Forms
Step 2: Create a new class
This part is pretty straight forward. For my purposes, instead of inheriting from the FieldViewModel, my class RichTextCheckboxViewModel inherited from CheckBoxViewModel.
Do not forget to:
- Add the [Serializable] attribute to the View Model
Here is my View Model:
using Sitecore;
using Sitecore.Data.Items;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
namespace SolutionName.Feature.FormsExtensions.Models
{
[Serializable]
public class RichTextChecboxViewModel : CheckBoxViewModel
{
public string RichText { get; set; }
protected override void InitItemProperties(Item item)
{
// on load of form
base.InitItemProperties(item);
RichText = StringUtil.GetString(item.Fields["RichText"]);
}
protected override void UpdateItemFields(Item item)
{
// upon save
base.UpdateItemFields(item);
item.Fields["RichText"]?.SetValue(RichText, true);
}
}
}
Step 3: Create the razor view file
So you can just create an MVC Razor View here, but you will likely not get all the nice bells and whistles. If you go dig into the deployed Sitecore folders where your site is hosted in IIS, and for instance search for CheckBox.cshtml, you will find the the rendering view used for the Forms Builder developed by Sitecore. I found the exploration of all of their cshtml to be enlightening with how they are wiring up Validation and Tracking with the Sitecore Forms. Adding these pieces in later feels like a strange after thought, when it is something you can probably do as you are building your Razor View the first time.
Peruse the views that come with Sitecore, and get a better idea of how you want to leverage the same or similar capabilities. One of the big reasons anybody would want to use Sitecore Forms is because it includes all the bells and whistles of tracking and analytics out of the box. It just makes sense to take the time to incorporate these into what you are developing the first time around.
My razor view looks like the below snippet, which is pretty much just a copy-paste of the original checkbox view from Sitecore, with the @Html.Raw(Model.RichText) tossed in. Notice all the wonderful extra Sitecore tracking attributes and tagging.
@using Sitecore.ExperienceForms.Mvc.Html
@model SolutionName.Feature.FormsExtensions.Models.RichTextChecboxViewModel
<label class="@Model.LabelCssClass">
<input type="checkbox" id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass" @if (Model.Value) { <text> checked="checked" </text> } value="true" data-sc-tracking="@Model.IsTrackingEnabled" data-sc-field-name="@Model.Name" @Html.GenerateUnobtrusiveValidationAttributes(m => Model.Value) />@Html.DisplayTextFor(t => Model.Title)
@Html.Raw(Model.RichText)
<input type="hidden" name="@Html.NameFor(m => Model.Value)" value="false" />
</label>
@Html.ValidationMessageFor(m => Model.Value)
Make sure to at least add your Razor View file to a base path of /Views/FormBuilder. This will save time later, as this is the base path it starts looking for form components to go. For simplicity, I just added mine to the same as those that Sitecore uses /Views/FormBuilder/FieldTemplates.
Steps 4: Create the sections for the Form elements pane
This talks about how to create the Details, Validation, Styling, and Advanced settings that go along with your shiny new custom Sitecore Form Element. This work occurs in the Core Database.
The walkthrough uses Sitecore Rocks, so pull that down and use it. Follow the directions, BUT, do not move on until you come back here.
Configure the field editor parameters is the next set of steps. Do not start them, yet.
1. Go to the very first item you created with the Form Parameters template. Copy and save the Item Id for that Item. You will need it later. I put mine into a quick notepad.
Note: We will need this Item Id for Step 6: Create the field type item.
2. You have have noticed that the directions do not discuss specifically creating the other Form Sections: Validation, Styling, and Advanced settings.
3. If you want these other areas for your custom Sitecore Form Element, the easiest thing to do is to navigate to the same path in the Content Editor, and copy these Form Sections from another item. If you do a little poking around, you will discover they are all set up the same way.
Notice that Validation, Styling, and Advanced setting reference Parameters that sit over beneath the Common folder: /Sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common
Below is the discrepancy for finding the Sitecore Items you are working on in Sitecore Rocks vs. doing it Content Editor.
So everything you just did in Sitecore Rocks follows this path: /Sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings
In the Sitecore Content Editor the same path looks a little different because some of the items have different display names: /Sitecore/client/Applications/Forms/Components/Layouts/PropertyGridForm/PageSettings/Property Editor Settings
Step 5: Configure the field editor parameters
Step 1 in here has you open "Width", in my case, the Rich Text : FormTextBox Parameters item below my Details : Form Section Item, which lives below my RichTextCheckbox : Form Parameters.
Scroll down to the Form section of your item, and make special note here. The binding configuration uses camelCase. I know the walkthrough discusses it. I am doing it again here for emphasis. For example:
- thisIsMyValue
- youShouldTypeItLikeThis
Step 2 says "in the Details section". This is confusing.
This is confusing. They mean, go and open up the Sitecore item you named Details : Form Section.
Follow the directions for the Configuration Item.
For the Control Definitions, the walkthrough just breezes over this. Take a look at the Details items below the other Form Parameters in this list. You will quickly notice that they often include other Parameters.
It is not until Step 3, that the walkthrough discusses copying and adjusting Form Sections from other Editors: Validation, Styling, and Advanced Settings. Even then, it really only provides guidance on how to add Styling.
Read through and take the time to fiddle with the Form Sections.
Step 6: Create the field type item
This is where it all comes together.
Add your Field Type item to the Basic folder as discussed in Step 1. Sitecore Forms uses the Basic folder as the datasource inside of the Forms Editor. I expect that there is a way to add more custom data sources, but I have not got that far yet.
Step 3 details editing some of the fields.
View Path: As discussed earlier when adding the Razor view, this path assumes a base of /Views/FormBuilder
Model Type: This is the namespace path to your ViewModel
Property Editor: Remember that Item Id I told you to save earlier? Ignore the image in the walkthrough. The cake is a lie.
The dropdown will not let you paste the Item Id from earlier into the Property Editor field.
So... Change your View to Raw values, and Paste that Item Id right into the Property Editor field. When you hit Save, it will throw a Broken Link Error. Ignore it.
If you do not believe me about that Item Id, take a look at the Property Editor field on the other default Sitecore Items. You can compare and find that they are pointed at the specific Form Parameter items over in the Core database.
The walkthrough also discusses fiddling with the icon and color it appears on the menu in the Sitecore Forms editor.
The walkthrough is done, BUT we are not.
There is one more for you. Just below the Property Editor, is a Data section with a Field Template. It is a dropdown that points to the Field Template folder we discussed at the very beginning of this whole thing: sitecore/Templates/System/Forms/Fields
As long as you followed the directions here and put your Field Template in that folder, it will be in this dropdown list for the Field Type you are creating right now.
I am excited that I made this work, as I truly enjoy the freedom and power that Sitecore 9 Forms can offer, and really want to leverage what it can do!
---------------------------------------------------------------------------------------------------------------
Shameless Plug: This is me - Feel free to hit me up if you have any questions, comments, or feel free to chime in with your own experiences or challenges along the way. Thank you for swinging by!