Access Context Item on Sitecore Forms using a Value Provider

There are many instances where we might require knowing which Sitecore page a particular form was being submitted from. When we author a custom Submit Action, we could use this information for further processing based on business requirements in place. 

In Sitecore forms Submit Actions, while we do have OOTB (out of the box) means to access the current form ID, it does not provide us with the current page guid in a straightforward way. 

One way to determine the context item from within a submit action, would be to use the HTTP_REFERER parameter from HttpContext – which gives us the URL of the page from where the request was triggered. Following this, we would need to try and resolve this URL to the item. While this is definitely feasible, it comes with its own sets of caveats and challenges. Between language embedding, case discrepancies, HTML encoding and using space replacement characters – there are a lot of scenarios which need to be handled to make the logic to resolve the item id from URL fool proof. 

Using a Value Provider in this case, is a much cleaner solution without leaving any room for ambiguity. 

Implementation: 

In this approach, we would create a hidden text field (hidden using appropriate CSS class) and populate the text field with the context item guid using a Value Provider. 

Create the model for the Value Provider: 

using Sitecore.ExperienceForms.ValueProviders; 

namespace sc101.Foundation.Forms 
{ 
    public class ContextValueProvider : IFieldValueProvider 
    { 
        public object GetValue(string parameters) 
        { 
            return Sitecore.Context.Item?.ID.ToString(); 
        } 
        public FieldValueProviderContext ValueProviderContext { get; set; } 
    } 
} 

Create the Value Provider using the template /sitecore/templates/System/Forms/Value Provider in Sitecore – /sitecore/system/Settings/Forms/Value Providers, linking it to the model above: 

To tie it all together, select the value provider on a text field on the Sitecore form: 

You can hide this input field using css as needed: 

Another great thing about this solution is that it is a one-time only implementation and can be used across all your forms as needed. 

Now that this is all wired up, you will be able to access the context item id in your custom save action like any other form field. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s