Walkthrough: Creating a custom rating element with property editor
Sitecore Forms includes default form elements that you can drag and drop onto your form. This walkthrough describes how to implement a custom rating control element using an existing plugin called jQuery Bar Rating and how to set additional properties. The result of following this walkthrough is a rating element with setting options:
This walkthrough describes how to:
Download and prepare the source files
This walkthrough uses an example of a rating element. To execute the steps on your local installation, you must download and prepare the source files.
To work with the jQuery Bar rating:
-
Navigate to http://antenna.io/demo/jquery-bar-rating/examples/
-
On the site, scroll down to the bottom of the page and click the download link.
-
Download and unpack the files.
-
Copy the following files:
-
jquery.barrating.min.js
-
jquery.barrating.min.js.map
-
-
Navigate to Sitecore
modules/Web/ExperienceForms/scripts/barrating
and paste the files. -
Navigate to the jquery-bar-rating-master/themes folder that you downloaded and copy the themes.
-
In the barrating folder, create a themes folder and paste the barrating/themes folder:
-
In the Content Editor, navigate to /sitecore/templates/Systems/Forms/Form and select the _Standard values item.
-
In the Settings section, in the Scripts field, add
|barrating/jquery.barrating
-
To load the form scripts and styles, they must be in an outer file layout. Therefore, add the
@Html.RenderFormStyles()
and@Html.RenderFormScripts()
statements to your outer layout.RequestResponsexml@using Sitecore.Mvc @using Sitecore.ExperienceForms.Mvc.Html @using Sitecore.Mvc.Analytics.Extensions @{ Layout = null; } <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>@Html.Sitecore().Field("title", new { DisableWebEdit = true })</title> @Html.Sitecore().VisitorIdentification() @Html.RenderFormStyles() @Html.RenderFormScripts() </head> <body> @RenderBody() </body> </html>
Create the field type item
A Sitecore item defines each form element. For a custom element to appear in the Form elements pane, you must create a new item. You can create a new item or duplicate an existing item. Because the jQuery bar rating plugin uses a select field, it is convenient to use the list element as the basis.
Like the drop-down list element, the jQuery Bar Rating plugin uses a select field:
To create the field type item by duplicating an existing item:
-
Navigate to the /sitecore/system/Settings/Forms/Field Types/Lists folder, right-click the Dropdown list item and click Duplicate.
-
Rename the item and the display name to Rating.
-
In the Appearance section, edit the following fields:
-
Icon – select the icon that will appear in the Forms elements pane. For example, OfficeWhite/32x32/star.png.
-
BackgroundColor – select the background color for the icon that will appear in the Form elements pane. For example, Grass.
-
Sortorder – to make the rating element appear last in the List section of the Form elements pane, set the sort order to 1200.
NoteIf the field does not display as expected, on the ribbon, on the View tab, select the Standard Fields check box. This shows all the fields from the Standard template on every item that you open.
-
Create a new field template
A Sitecore template defines form elements. For this example, to set additional properties, you must create a new field template for the Rating element to define those properties.
To add a template:
-
In the Sitecore Content Editor, navigate to sitecore/Templates and create a new folder. For example, the Fields folder.
-
Click the new folder and then click New Template.
-
Enter the name Rating, select the Dropdown List as the base template and click Next.
-
Click the new template, and on the Builder tab, add a section called Options. For example, to add settings for the rating element, add the following check boxes:
-
Show Values
-
Show Selected Rating
-
Reverse
-
Hover State
-
-
Save the template.
-
On the Content tab, in the Appearance section, set the Icon field value to Office/32x32/star.png
-
On the ribbon, in the Options tab, click Standard values.
-
In the Options section, select the Show Selected Rating and Hover State check boxes. This means that these properties will be checked by default.
-
In the Field Type field, change the field type to Rating.
-
Go to the rating item that you created in the Create the field item section and set the Field template value to Rating.
Create a new class
Now you can create the logic for the View model by creating a new class that derives from the FieldViewModel class. You can control how the form element displays by arranging the HTML and inserting your own CSS classes.
To add the new class:
-
In Visual Studio, create a new class library project. For example, Sitecore.ExperienceForms.Samples.
-
Reference the
Sitecore.ExperienceForms.Mvc
assembly. -
Add the
RatingViewModel
class. -
Inherit
DropDownListViewModel
and mark the class Serializable.RequestResponseshell/// <summary> /// Defines the rating view model. /// </summary> /// <seealso cref="Sitecore.ExperienceForms.Mvc.Models.Fields.DropDownListViewModel" /> [Serializable] public class RatingViewModel : DropDownListViewModel { }
-
In the Models folder, create a new
FieldNames
class and define a constant for each property that you want to set.RequestResponseshellpublic static class FieldNames { public const string ShowValues = "Show Values"; public const string ShowSelectedRating = "Show Selected Rating"; public const string Reverse = "Reverse"; public const string HoverState = "Hover State"; }
-
For each field in the rating template, create a property in the RatingViewModel class.
RequestResponseshell/// <summary> /// Gets or sets a value indicating whether the rating texts will be displayed on the bars. /// </summary> public bool ShowValues { get; set; } /// <summary> /// Gets or sets a value indicating whether the selected rating text will be displayed next to the control. /// </summary> public bool ShowSelectedRating { get; set; } /// <summary> /// Gets or sets a value indicating whether the ratings will be reversed. /// </summary> public bool Reverse { get; set; } /// <summary> /// Gets or sets a value indicating whether the control changes state on hover. /// </summary> public bool HoverState { get; set; }
-
To read the field values, override
InitItemProperties
in theRatingViewModel
class.RequestResponseshell/// <summary> /// Initializes the model properties from the <paramref name="item" />. /// </summary> /// <param name="item">The item.</param> protected override void InitItemProperties(Item item) { Assert.ArgumentNotNull(item, nameof(item)); base.InitItemProperties(item); ShowValues = MainUtil.GetBool(item.Fields[FieldNames.ShowValues]?.Value, false); ShowSelectedRating = MainUtil.GetBool(item.Fields[FieldNames.ShowSelectedRating]?.Value, false); Reverse = MainUtil.GetBool(item.Fields[FieldNames.Reverse]?.Value, false); HoverState = MainUtil.GetBool(item.Fields[FieldNames.HoverState]?.Value, false); }
-
To save the field values, override
UpdateItemFields
.RequestResponseshell/// <summary> /// Updates the <paramref name="item" /> fields using the model properties. /// </summary> /// <param name="item">The item.</param> protected override void UpdateItemFields(Item item) { Assert.ArgumentNotNull(item, nameof(item)); base.UpdateItemFields(item); item.Fields[FieldNames.ShowValues]?.SetValue(ShowValues ? "1" : string.Empty, true); item.Fields[FieldNames.ShowSelectedRating]?.SetValue(ShowSelectedRating ? "1" : string.Empty, true); item.Fields[FieldNames.Reverse]?.SetValue(Reverse ? "1" : string.Empty, true); item.Fields[FieldNames.HoverState]?.SetValue(HoverState ? "1" : string.Empty, true); 9. To reference the new Rating view model in the Rating field type, navigate to
-
To reference the new Rating view model in the Rating field type, navigate to /sitecore/system/Settings/Forms/Field Types/Lists/Rating and in the Model Type field enter:
Sitecore.ExperienceForms.Samples.Models.RatingViewModel,Sitecore.ExperienceForms.Samples
Create the razor view file
The next step is to create the razor view file:
-
Navigate to Website/Views/FormBuilder/FieldTemplates/Samples and create a new razor file called
Rating.cshtml
. -
Add the code. For example, for the rating element:
RequestResponseshell@using Sitecore.ExperienceForms.Mvc.Html @model Sitecore.ExperienceForms.Samples.Models.RatingViewModel @if (!string.IsNullOrEmpty(Model.CssClass)) { var themePath = "/sitecore modules/Web/ExperienceForms/css/barrating/themes/" + Model.CssClass + ".css"; var allowEmpty = Model.ShowEmptyItem.ToString().ToLowerInvariant(); var deselectable = (Model.ShowEmptyItem && !Model.Required).ToString().ToLowerInvariant(); <link rel="stylesheet" href="@themePath"/> <script type="text/javascript"> $(function() { var $el = $("#@Html.IdFor(m => Model.Value)"); if (typeof $el.barrating === "function") { $el.barrating({ theme: "@Model.CssClass", showValues: @Model.ShowValues.ToString().ToLowerInvariant(), showSelectedRating: @Model.ShowSelectedRating.ToString().ToLowerInvariant(), reverse: @Model.Reverse.ToString().ToLowerInvariant(), hoverState: @Model.HoverState.ToString().ToLowerInvariant(), deselectable: @deselectable, allowEmpty: @allowEmpty }); } }); </script> } <label for="@Html.IdFor(m => Model.Value)" class="@Model.LabelCssClass">@Html.DisplayTextFor(t => Model.Title)</label> <select id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" data-sc-tracking="@Model.IsTrackingEnabled" data-sc-field-name="@Model.Name" @Html.GenerateUnobtrusiveValidationAttributes(m=> m.Value)> @if (Model.ShowEmptyItem) { <option label=""></option> }@foreach (var item in Model.Items) { <option value="@item.Value" selected="@item.Selected"> @item.Text </option> } </select> @Html.ValidationMessageFor(m => Model.Value)
-
To point the new rating field to the razor view file, navigate to /sitecore/system/Settings/Forms/Field Types/Lists/Rating and in the View Path field, add the location of the razor view file, in this example, FieldTemplates/Samples/Rating
Create the property editor
Now you can add the sections that appear in the Form elements pane. For this example, the Single-line text element contains the following sections: Details, Validation, Styling, and Advanced settings.
For the example in this walkthrough, you must have the Sitecore Rocks Visual Studio plugin. The plugin is compatible with Visual Studio 2019 or earlier.
In this example, we based the Rating element on the Dropdown list element and we will be duplicating the property editor that already exists for the Dropdown list element.
To add sections to the Form elements pane:
-
In Sitecore Rocks, expand the core database and navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/DropDownList
-
Duplicate the item and change the name to Rating.
NoteThe Dropdown list element contains child items that define the controls in the List items expander in the property editor. After duplicating, the Rating/ListItems will refer to the DropDownList/ListItems in the ControlsDefinitions field value. To customize the controls labels or just to disconnect the rating designer from the drop-down list designer, you can update the ControlsDefinition field value with the IDs of the duplicated child items.
-
Right-click the Styling item, click Add and click New Item.
-
In the Add New Item dialog box, search for and select the Form parameters template.
-
Click Add three times and enter the item names: ShowValues, ShowSelectedRating, HoverState, Reverse.
-
In the Styling section, double-click the ShowValues item and edit the following fields:
-
Label – enter the check box label Show values
-
IsLabelOnTop – select to ensure styling consistency.
-
BindingConfiguration – enter showValues
NoteOptionally, you can enter the help text information.
-
-
Set the values for the three other check box parameter items accordingly.
-
Next, you must include the IDs of the items created in the ControlDefinitions field. Navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/Rating/Styling and add the previously created items
-
Finally, you must reference the new property editor in the Rating field item. Navigate to /sitecore/system/Settings/Forms/Field Types/Lists/Rating item and in the Property Editor field, select the Rating property editor.
The rating element is now available in the Form elements pane:
When you drag the Rating element onto the form canvas, the new styling options are available:
Optional: Add another property editor for the themes
The themes of the bar rating plugin that you added earlier are available after entering the class in the CSS class field. If you prefer to have the themes available from a drop-down box, you can add another control to the rating property editor. A quick overview of the tasks:
-
Use the ListItem template and add ten items for the ten themes.
-
Edit the items and enter the rating theme name in the Value field.
-
Adjust the FormSection style:
-
Add the child item Theme using the FormDropList Parameters template
-
StaticData - enter the ID of the RatingThemes folder
-
ValueFieldName - Value
-
FormLabel - Theme
-
IsLabelOnTop - selected
-
BindingConfiguration - cssClass property
-
-
In the ControlDefinitions field reference the new theme. Because you added the CSS class binding in the Styling FormSection, you must remove it here.