I have added a hidden field on a Sitecore (9.2) form. I want to assign some value to that hidden field when the form loads. Can anyone please tell me how I can achieve that?
2 Answers
You need to add a custom field in Sitecore forms. You may refer to some blogs related to it. For example in my case I've created a custom Sitecore field called "hidden field". When I add it to Sitecore form, it gives me options to add some values like this.
And in the code behind, I bind these values like this.
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
namespace Site.Feature.Forms.Forms.Controls.HiddenField
{
[System.Serializable]
public class HiddenFieldModel : InputViewModel<string>
{
public string FromEmail { get; set; }
protected override void InitItemProperties(Item item)
{
Assert.ArgumentNotNull(item, "item");
base.InitItemProperties(item);
FromEmail = item?.Fields["From Email"]?.Value;
}
protected override void UpdateItemFields(Item item)
{
Assert.ArgumentNotNull(item, "item");
base.UpdateItemFields(item);
var fromEmail = item.Fields["From Email"];
if (fromEmail != null)
fromEmail.SetValue(FromEmail, true);
}
}
}
And on the view, you can access the value like this.
@using System.Web.Mvc.Html
@model Site.Feature.Forms.Forms.Controls.HiddenField.HiddenFieldModel
<input type="hidden" id="@Html.IdFor(m => Model.FromEmail)" name="@Html.NameFor(m => Model.FromEmail)" value="@Model.FromEmail" />
Make sure your custom hidden field component supports the value provider mechanism.
You can create a value provider to fill the hidden field.
-
I have used existing hidden field on the form. how i can make that field support value provider mechanism? Commented Jan 28, 2020 at 21:47
-
By default, there is no hidden field component in Sitecore. So it's impossible to use the "existing hidden field". So either you have created a component yourself, or you have installed a module offering the hidden field functionality. If you use Sitecore Forms Extensions (SFE), the hidden field component of this module already supports the value provider. If you use another module not offering this functionlity you will have to do a feature request to the creator or switch to a module offering this functionality. Commented Jan 29, 2020 at 15:11