1

I understand that in order to add a script in Sitecore Forms, I must add it in the script field of the form. However, this could be cumbersome for the content editors since they would have to add the script every time they make a form. Plus, this new custom javascript does not need to be in all forms but only in select forms where a particular field is added.

Is there a way to automatically add that custom script only when a particular field is added?

1 Answer 1

3

Just add the following processor to forms.renderField pipeline:

public class RenderFieldSpecificJavascript : MvcPipelineProcessor<RenderFieldEventArgs>
{
    public override void Process(RenderFieldEventArgs args)
    {
        if (args.RenderingSettings.FieldTypeId == "{4EE89EA7-CEFE-4C8E-8532-467EF64591FC}" // your custom field ID
            && HttpContext.Current.Items.Contains("ExperienceFormsScriptsKey"))
        {
            var dict = (Dictionary<string, IHtmlString>) HttpContext.Current.Items["ExperienceFormsScriptsKey"];
            dict["MyCustomField"] = new HtmlString("<script src=\"/my-custom-script.js\"></script>");
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <pipelines>
            <forms.renderField>

                <processor 
                    type="My.Assembly.Namespace.RenderFieldSpecificJavascript, My.Assembly" 
                    patch:before="processor[@type='Sitecore.ExperienceForms.Mvc.Pipelines.RenderField.IncludeConditions, Sitecore.ExperienceForms.Mvc']"/>

            </forms.renderField>
        </pipelines>
    </sitecore>
</configuration>

It will render your script at the end of the <body>:

enter image description here

2
  • Would it be cleaner if I did this inside a pipeline?
    – Lala
    Feb 19, 2023 at 6:30
  • 1
    @Lala code updated
    – Marek Musielak
    Feb 19, 2023 at 18:03

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.