Sitecore Experience Management

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:

Forms rating example
FORMS-rating-element-in-pane-example.png

This walkthrough describes how to:

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:

  1. Navigate to http://antenna.io/demo/jquery-bar-rating/examples/

  2. On the site, scroll down to the bottom of the page and click the download link.

  3. Download and unpack the files.

  4. Copy the following files:

    • jquery.barrating.min.js

    • jquery.barrating.min.js.map

  5. Navigate to sitecore modules/Web/ExperienceForms/scripts/barrating and paste the files.

  6. Navigate to the jquery-bar-rating-master/themes folder that you downloaded and copy the themes.

  7. In the barrating folder, create a themes folder and paste the barrating/themes folder:

    FORMS-barrating-themes-folder.png
  8. In the Content Editor, navigate to /sitecore/templates/Systems/Forms/Form and select the _Standard values item.

  9. In the Settings section, in the Scripts field, add |barrating/jquery.barrating

    FORMS-barrating-script.png
  10. 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.

    
    @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>
    
    

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:

FORMS-select-field.png

To create the field type item by duplicating an existing item:

  1. Navigate to /sitecore/system/Settings/Forms/Field Types/Lists folder, right-click the Dropdown list item and click Duplicate.

  2. Rename the item and the display name to Rating.

  3. 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.

    Note

    If 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.

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:

  1. In the Sitecore Content Editor, navigate to sitecore/Templates and create a new folder. For example, the Fields folder.

  2. Click the new folder and then click New Template.

  3. Enter the name Rating, select the Dropdown List as the base template and click Next.

    FORMS-select-name.png
  4. 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

      FORMS-Builder-options.png
  5. Save the template.

  6. On the Content tab, in the Appearance section, set the Icon field value to Office/32x32/star.png

  7. On the ribbon, in the Options tab, click Standard values.

  8. In the Options section, select the Show Selected Rating and Hover State check boxes. This means that these properties will be checked by default.

  9. In the Field Type field, change the field type to Rating.

  10. Go to the rating item that you created in the Create the field item section and set the Field template value to Rating.

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:

  1. In Visual Studio, create a new class library project. For example, Sitecore.ExperienceForms.Samples.

  2. Reference the Sitecore.ExperienceForms.Mvc assembly

  3. Add the RatingViewModel class.

  4. Inherit DropDownListViewModel and mark the class Serializable.

    
    /// <summary>
    /// Defines the rating view model.
    /// </summary>
    /// <seealso cref="Sitecore.ExperienceForms.Mvc.Models.Fields.DropDownListViewModel" />
    [Serializable]
    public class RatingViewModel : DropDownListViewModel
    {
     
    }
    
  5. In the Models folder, create a new FieldNames class and define a constant for each property that you want to set.

    
    public 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";
    
    }
    
    
  6. For each field in the rating template, create a property in the RatingViewModel class.

    
    /// <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; }
    
    
  7. To read the field values, override InitItemProperties in the RatingViewModel class.

    /// <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);
    }
    
  8. To save the field values, override UpdateItemFields.

    /// <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 
  9. 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

    FORMS-Model-type-field.png

The next step is to create the razor view file:

  1. Navigate to Website/Views/FormBuilder/FieldTemplates/Samples and create a new razor file called Rating.cshtml.

  2. Add the code. For example, for the rating element:

    
    @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)
    
    
  3. 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

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.

Note

For the example in this walkthrough, you must have the Sitecore Rocks Visual Studio plug-in.

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:

  1. In Sitecore Rocks, expand the core database and navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/DropDownList

  2. Duplicate the item and change the name to Rating.

    Note

    The 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.

  3. Right-click the Styling item, click Add and click New Item.

  4. In the Add New Item dialog box, search for and select the Form parameters template

  5. Click Add three times and enter the item names: ShowValues, ShowSelectedRating, HoverState, Reverse.

  6. 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

    Note

    Optionally, you can enter the help text information.

  7. Set the values for the three other check box parameter items accordingly.

  8. 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

  9. 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:

    FORMS-rating-element.png

    When you drag the Rating element onto the form canvas, the new styling options are available:

    FORMS-rating-element-in-pane-example.png

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:

  1. Use the ListItem template and add ten items for the ten themes.

    FORMS-add-new-item-listitems.png
  2. Edit the items and enter the rating theme name in the Value field.

  3. 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

      FORMS-staticdata.png
      FORMS-formdata.png
  4. In the ControlDefinitions field reference the new theme. Because you added the CSS class binding in the Styling FormSection, you must remove it here.

    FORMS-formdefinition.png