Sunday, May 31, 2015

Saving Form data with the Web Forms For Marketers MVC Form API

As many people have noticed with the Web Forms For Marketers MVC Forms the data does not serialize correctly so using custom save actions you cannot get the data from the form correctly.

There are a few rather complex workarounds for this mostly involving parsing the form from the form values in the http response.

The easiest solution to this issue is to create your own Form Processor which you can inject with a configuration file.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <wffm>
      <formProcessors>
        <processor type="MyNamespace.Forms.MVC.Processors.FormProcessor, MyNamespace.Forms.MVC" />
      </formProcessors>
    </wffm>
  </sitecore>
</configuration>

The processor itself is actually quite easy to write you simply need a class that inherits Sitecore.Forms.MVC.Processors.FormProcessor, then you can implement your save action in the FormSuccessValidation event.

namespace MyNamespace.Forms.MVC.Processors
{
    public class FormProcessor : FormProcessor
    {
        public FormProcessor()
        {
            SuccessValidation += FormSuccessValidation;
        }
 
        private void SaveForm(FormModel form)
        {
            var Fields = form.Sections.SelectMany(i => i.Fields);
        }
 
        public void FormSuccessValidation(object source, FormEventArgs args)
        {
            SaveForm(args.Form);
        }
    }
}

You can see from my code that you can access the fields through the given model in the form.Sections property.  

I find that this is much easier to implement than a custom save action (though it will not show up in the drop down list which may be a problem for some people, you can use this to store the data to access in a custom save action).  

If you have any questions related to Web Forms For Marketers please don't hesitate to ask as I have spent a lot of time in that code lately.

No comments:

Post a Comment