0

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 2

2

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.

enter image description here

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" />
0

Make sure your custom hidden field component supports the value provider mechanism.

You can create a value provider to fill the hidden field.

https://doc.sitecore.com/developers/93/sitecore-experience-manager/en/walkthrough--setting-up-a-value-provider-for-prefilling-forms.html

2
  • I have used existing hidden field on the form. how i can make that field support value provider mechanism? 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. Jan 29, 2020 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.