Creating a hidden field for Sitecore Forms

Sitecore Forms is a versatile tool included with Sitecore 9. Its intuitive controls make it simple for content authors to create their own forms and include them in a page by using the Mvc Form rendering.

In a recent project, I found myself needing to fulfill a customer request to include the URL of the page where the form was filled out as part of the submitted form data. Normally a developer would add a hidden field to the standard HTML form, and then use JavaScript or something similar to populate the “value” attribute of that field with the current window location.

However, out-of-the-box Sitecore Forms doesn’t come with a hidden field type for authors to use. Thankfully, Sitecore provides documentation on how to create a custom form element for Sitecore Forms.

Following this tutorial gets us most of the way there.

However, I was then running into a problem – the value I’d populated in the form wasn’t coming across to the server. I found that someone else was having a similar issue in trying to get a Google Recaptcha to submit with their Sitecore form, as described by this blog post.

Here, instead of using the FieldViewModel class, they inherit from the specific MultipleLineTextViewModel. Since we only need a single line of text to hold a URL, we can use StringInputViewModel, giving us this code:

[Serializable]
	public class ReferringURLViewModel : StringInputViewModel
	{
		protected override void InitItemProperties(Item item)
		{
			base.InitItemProperties(item);
		}

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

Then we can create the view for the field as follows:

@model Foundation.Forms.Models.ReferringURLViewModel
<input id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass" type="hidden" value="" />
<script type="text/javascript">
	var hiddenField = document.getElementById(@Html.Raw("\"" + Html.IdFor(m => Model.Value) + "\""));
	hiddenField.value = window.location.href;
	var parent = hiddenField.parentNode;
	if (parent.classList.contains("sc-formdesign-fieldcontainer")) {
		var textDiv = document.createElement("div");
		textDiv.innerHTML = "(Hidden referring URL field)";
		parent.appendChild(textDiv);
	}
</script>

The JavaScript here both sets the value of the hidden field to window.location.href, and adds a text div if the field is being displayed inside the Sitecore Forms Designer, so that the field can easily be found.