Search code examples
asp.net-mvcumbraco7umbraco-forms

Custom method on form submission with Umbraco Forms


What I'm trying to achieve is to customise what happens during the HttpPost/OnSubmit of a form created with Umbraco Forms, whilst still maintaining the default behaviour of the form and any subsequent workflow.

In my specific scenario, I need to be able to analyse the input of the form and based on that input I will send the user to a different "thank you" page, whilst also storing some elements of the originally submitted form in TempData.

I've tried the following:

  • I've tried to create a DocType controller (RenderMvcController), but this only allows you to override the HttpGet, and not Post.

  • I cannot use a SurfaceController as I lose the functionality of the module, Umbraco Forms.

  • I've tried to use a custom workflow, but this runs asynchronous to the user's journey and I cannot change their experience.

There isn't much useful documentation available for this at all and I'm finding this task more difficult than I expected it to be.


Solution

  • In order to add a custom procedure after the submission of the form, and based on this procedure change the user journey you must do the following:

    Create a new controller and inherit from UmbracoFormsController and override the OnFormHandled method

     public class CustomUmbracoFormsController : UmbracoFormsController
     {
          protected override void OnFormHandled(Form form, FormViewModel model)
          {
               // Find the field in the form, then search for a matching value
               var field = form.AllFields.FirstOrDefault(x => x.Alias == "deliveryOptions");
               var fieldValue = model.FormState[field.Id.ToString()].GetValue(0).ToString();
    
               // Add the value to the TempData
               TempData["deliveryOptions"] = fieldValue;
          }
     }
    

    The above is a basic implementation that doesn't account for NULL

    Update the reference to UmbracoFormsController in /Views/Partials/Forms/Form.cshtml with your new controller from above.

    ...
    @using (Html.BeginUmbracoForm<CustomUmbracoFormsController>("HandleForm"))
    ...
    

    In the above example we analyse the form data and store some information in the TempData, we can set the form to redirect to a generic thank you page in which we can analyse the values in the TempData and change the view the user sees.

    Also, if you are making changes to the Form values and what these to be updated, you'll need the Record Guid, which you can retrieve from TempData["Forms_Current_Record_id"] in conjunction with a new RecordStore object.