Range Slider for Sitecore Forms

Sitecore Developer
Talk with our tech expert & find initial solutions the challenge, that is currently crucial for your business

Sitecore Forms which were introduced with Sitecore 9 are so much better than WFFM and they are growing with each new version of Sitecore. Let’s just remember that if we need more customized features or fields, then we will have to create logic by ourselves, so I’ll show an example of how to create Range Slider field. 

range slider

Range slider

Range slider is rarely used in forms, but it could be used in few situations like as an age selector or in a donation form for selecting amount of money to donate.

Where to start?

Obviously, before starting work, you’ll have to get to know how to add new fields in Sitecore Forms. You can read about it here.

If you are familiar with that, then we have to find a library with slider to use. Every slider has its own merit, so it’s best to test it before making your choice. Based on the chosen library, you will have some options and HTML to use. I’m going to use Range Slider.

It’s up to you how many options you’ll want to use, based on that you’ll create your properties in model/fields in the template. I’ll use:

  • Min – setting min value
  • Max – setting max value
  • From – number to start off with
  • Step – ho many ticks to step with each move
  • Prefix – prefix to tooltip
  • Postfix – postfix to tooltip
  • Grid – checkbox to show or hide grid
  • Skin – prepopulated dropdown with available slider skins

1. Additional files

Don’t forget to add additional JS and CSS files to your project! Path for them in project would be:

  • CSS – /sitecore modules/Web/ExperienceForms/css/ion.rangeSlider.min.css
  • JavaScript – /sitecore modules/Web/ExperienceForms/scripts/ion.rangeSlider.min.js

Thanks to that, you will be able to easily add them to your form (or Form template if you want to add them to every form by default):

range slider for sitecore forms

2. Field Template

Simple template for our model with base templates:

  • /sitecore/templates/System/Forms/Fields/Field
  • /sitecore/templates/System/Forms/Label Settings – to allow using of Label and Label Css Class

field templates sitecore

3. Model

Don’t inherit FieldViewModel class! It’s okay to use it for field which won’t have any input, but for input fields, just inherit InputViewModel<T> class (which inherits FieldViewModel). Trust me on this, it will help you avoid problems later with conditions and validations.

Then add properties in model based on what you’ll use in view (to set slider) and of course set them properly in InitItemProperties and UpdateItemFields methods.

My model will look like this:

public class RangeSliderViewModel : InputViewModel<string>
{
	public int Minimum { get; set; }
	public int Maximum { get; set; }
	public int Start { get; set; }
	public int Step { get; set; }
	public string Prefix { get; set; }
	public string Postfix { get; set; }
	public string Skin { get; set; }
	public bool Grid { get; set; }

	protected override void InitItemProperties(Item item)
	{
		base.InitItemProperties(item);

		Minimum = MainUtil.GetInt(item.Fields["Minimum"]?.Value, 0);
		Maximum = MainUtil.GetInt(item.Fields["Maximum"]?.Value, 0);
		Start = MainUtil.GetInt(item.Fields["Start"]?.Value, 0);
		Step = MainUtil.GetInt(item.Fields["Step"]?.Value, 0);
		Prefix = StringUtil.GetString(item.Fields["Prefix"]);
		Postfix = StringUtil.GetString(item.Fields["Postfix"]);
		Skin = StringUtil.GetString(item.Fields["Skin"]);
		Grid = MainUtil.GetBool(item.Fields["Grid"]?.Value, false);
	}

	protected override void UpdateItemFields(Item item)
	{
		base.UpdateItemFields(item);

		item.Fields["Minimum"]?.SetValue(Minimum.ToString(CultureInfo.InvariantCulture), true);
		item.Fields["Maximum"]?.SetValue(Maximum.ToString(CultureInfo.InvariantCulture), true);
		item.Fields["Start"]?.SetValue(Start.ToString(CultureInfo.InvariantCulture), true);
		item.Fields["Step"]?.SetValue(Step.ToString(CultureInfo.InvariantCulture), true);
		item.Fields["Prefix"]?.SetValue(Prefix, true);
		item.Fields["Postfix"]?.SetValue(Postfix, true);
		item.Fields["Skin"]?.SetValue(Skin, true);
		item.Fields["Grid"]?.SetValue(Grid ? "1" : string.Empty, true);
	}
}

4. Form elements

I won’t go into details as it’s explained in documentation, but based on model RangeSlider will have those items (you can copy some of them from other fields):

form elements sitecore

We’ll have to create:

  • Minimum, Maximum, Start, Step, Prefix, Postfix – FormTextBox Parameters template.
  • Grid – FormCheckBox Parameters template
  • Skin – FormDropList Parameters template. Besides normal stuff it will need StaticData field set to ListItems folder with our skins (explained in next point) and ValueFieldName field set to Value.

skin dropdown field sitecore

In details, select all subitems. I also selected FieldName and Label (from /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Details/ folder):

form properties details sitecore

Styling item can be copied, but make sure it will have CssClass and LabelCssClass selected:

styling options sitecore

5. View

We’ll need to use our Model, initialize Range Slider and add HTML. Input CSS class needs to be unique in case of having multiple fields in one form thus I added @("js-range-slider-" + Model.Name) CSS class (of course you can use whatever you want, like ID, as long as it works). With all that in mind, the view will look like this:

@model DemoProject.Model.RangeSliderViewModel

<label for="@Html.IdFor(m => Model.Value)" class="@Model.LabelCssClass">@Html.DisplayTextFor(t => Model.Title)</label>
<input id="@Html.IdFor(m => Model.Value)"
       name="@Html.NameFor(m => Model.Value)"
       class="@Model.CssClass js-range-slider @("js-range-slider-" + Model.Name)"
       value="@Model.Value"
       data-sc-field-name="@Model.Name" />

<script type="text/javascript">
	$("@(".js-range-slider-" + Model.Name)").ionRangeSlider({
		min: @Model.Minimum,
		max: @Model.Maximum,
		from: @Model.Start,
		step: @Model.Step,
		@Html.Raw(string.IsNullOrEmpty(Model.Prefix)? "" : string.Format("prefix:\"{0}\",", Model.Prefix))
		@Html.Raw(string.IsNullOrEmpty(Model.Postfix) ? "" : string.Format("postfix:\"{0}\",", Model.Postfix))
		@Html.Raw(string.IsNullOrEmpty(Model.Skin) ? "" : string.Format("skin:\"{0}\",", Model.Skin))
		grid: @Model.Grid.ToString().ToLower()
	});
</script>

6. Field Type

As a last step, let’s create Field Type – field item which will be available to use in Form Editor. Our Range slider Field type will sit under path /sitecore/system/Settings/Forms/Field Types/Basic/Range slider and will be of /sitecore/templates/System/Forms/Field Type template. What have to be set inside:

  • View Path – my path is /Views/FormBuilder/CustomFields/RangeSlider.cshtml, so simple CustomFields/RangeSlider in field would be enough
  • Model Type – as usual it will be namespace and assembly
  • Property Editor – Form element from core DB, so what we created in point 4
  • Field Template – template item for model, so what we created in point 2

range slider sitecore forms

Result

Now we’ll have options to add Range slider field in our form.

range slider sitecore

Oh no…

I was a little bit suprised, because my slider was displayed as textbox and I couldn’t edit it. Why? It turned out that there is javascript error because of which slider wasn’t initialized:

jserror sitecore

I checked few others Slider libraries and there were other errors, so I had to fix it.

Oh, okay

Weirdly it happens only in Forms Editor and I managed to make a little hack to just initialize it only outside Forms Editor. Sitecore.Context.PageMode.IsNormal returns true in Forms Editor, so I had to check in js if Html doesn’t have data-sc-app attribute:

<script type="text/javascript">
    $(function () {
        if (typeof($("html").data('sc-app')) === 'undefined') {
            $(".js-range-slider").ionRangeSlider({
				...
            });
        }
    });
</script>

Oh yeah!

Now I’m able to edit settings:

range slider for sitecore

Form

Finally, after inserting our form on the page that is the result:

slider result sitecore

Summary

That’s it. Now you have Range Slider field for Sitecore Forms.

Would you like to talk with our experts about technology solutions for your business?

Rate this post
Sitecore Developer
Talk with our tech expert & find initial solutions the challenge, that is currently crucial for your business
Share on facebook
Share on linkedin

Share the article

Dawid Grybowicz

Software consultation

Fill in the form

The more information you can provide us, the better understanding we have of who will be perfect match for your chat.

Get a reply

Get a reply in only 2 hours and schedule your 15min call.

Receive recommendations

Receive an e-mail with recommendations crafted to your need & business.

Share on facebook
Share on linkedin

We use cookies to ensure you get the best experience on our website.