Custom Form Handlers

Platformus.Website extension offers the great forms features. You can describe your forms in the backend, and then render them and get user feedback on any frontend view. When user fills the form and clicks the Submit button, data is sent to a server and might be processed in any way you want. User input is handled by the implementations of the IFormHandler interface.

The selected implementation receives the form object, all the user input (string values by field objects), and all the attachments user has uploaded. Field values can be validated using the implementations of the IFieldValidator interface (you can use the ReCaptchaFieldValidator as an example).

It should return any IActionResult as the result.

Platformus has the only one built-in implementation of the IFormHandler interface: the EmailFormHandler class. It sends the user input to the specified email recipients.

Let’s implement our own form handler, which will just display the user input (but we could create some DB records as well). Create the DisplayUserInputFormHandler class inside the main web application project and implement the IFormHandler interface there:

public class DisplayUserInputFormHandler : IFormHandler
{
  public IEnumerable<ParameterGroup> ParameterGroups => new ParameterGroup[] { };
  public string Description => "Our own form handler.";

  public async Task<IActionResult> HandleAsync(HttpContext httpContext, string origin, Form form, IDictionary<Field, string> valuesByFields, IDictionary<string, byte[]> attachmentsByFilenames)
  {
    StringBuilder body = new StringBuilder();

    foreach (KeyValuePair<Field, string> valueByField in valuesByFields)
      body.AppendFormat("<p>{0}: {1}</p>", valueByField.Key.Name.GetLocalizationValue(), valueByField.Value);

    return new ContentResult() { Content = body.ToString() };
  }
}

Now, when our form handler class is added, navigate to the backend’s Content/Forms section and create or edit a form:

../_images/12.png

Please note, that our new form handler C# class is automatically resolved and added to the drop down list. Click the Save button.

Now navigate to /en/contacts and fill out the form:

../_images/22.png

Click the Send button. Output from our form handler is displayed:

../_images/32.png

We could return some view, redirect, or any other action result we need.

Form Handler Parameters and Parameter Groups

As well as the endpoints and data sources, form handlers support parameters and parameter groups. The implementation is absolutely the same, so please just take a look at the one for the endpoints. Also, please take a look at the built-in form handler to see how it uses this feature.