Dmitry helped me come up with this solution which uses the available global events for form rendering:
public class GlobalFormEventsModule
{
public static void RegisterEventHandlers() => FormWidgetRenderingConfiguration.GetConfiguration.Execute += GetConfiguration_Execute;
private static void GetConfiguration_Execute(object sender, GetFormWidgetRenderingConfigurationEventArgs e)
{
if (HttpContext.Current.Kentico().PageBuilder().EditMode || HttpContext.Current.Kentico().Preview().Enabled)
{
return;
}
string scripts = @"
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js""></script>
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js""></script>
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js""></script>
<script src=""~/Kentico/Scripts/forms/updatableFormHelper.js""></script>
";
if (e.FormComponents.Any(c => c.Definition.Identifier == USPhoneComponent.IDENTIFIER))
{
scripts += @"<script src=""~/Kentico/Content/FormComponents/USPhone/inputmask.js""></script>";
}
if (e.FormComponents.Any(c => c.Definition.Identifier == FileUploaderComponent.IDENTIFIER))
{
scripts += @"<script src=""~/Kentico/Content/FormComponents/FileUploader/file-uploader.js""></script>";
}
e.Configuration.FormWrapperConfiguration = new FormWrapperRenderingConfiguration
{
CustomHtmlEnvelope = MvcHtmlString.Create($"{scripts}{FormWrapperRenderingConfiguration.CONTENT_PLACEHOLDER}")
};
}
}
You can then call GlobalFormEventsModule.RegisterEventHandlers();
in the Global.asax.cs
.
This allows us to only call @Html.Kentico().PageBuilderScripts()
when the page is being rendered in Edit mode but still get the required form utility libraries loaded when a form is being rendered on the page for the Live site.
The <script>
elements get rendered directly before the <form>
element.