Display Web Forms for Marketers Form Submissions Outside of the Form Reports


After implementing Sitecore: Export to CSV/Excel of Web Form For Marketers Form (WFFM) Reports, now let’s render form reports in HTML format on front end.

This is useful if you want to show WFFM form reports out of the Sitecore in HTML format.

First I created a class to read form data & create HTML structure:

This class is creating dynamic HTML page with table and adding form data in created table.

public class CustomExportToHTML
{
     public string Process(FormItem form, FormPacket Packet)
     {
         Job job = Context.Job;
         if (job != null)
         {
              job.Status.LogInfo(ResourceManager.Localize("EXPORTING_DATA"));
         }
          // Creating HTML page structure with dynamically HTML tags
          StringWriter stringWriter = new StringWriter();
          HtmlTextWriter htmlDocument = new HtmlTextWriter(stringWriter);
          htmlDocument.Write("<!DOCTYPE html>");
          htmlDocument.AddAttribute("xmlns", "http://www.w3.org/1999/xhtml");
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Html);
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Head);
          htmlDocument.AddAttribute("type", "text/css");
         // Add style tag inside head tag to add styling for table
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Style);
          htmlDocument.Write("table, th, td {border: 1px solid black;border-collapse: collapse;margin: 20px auto 0;padding: 7px;}th {background-color: #a0a0a0;}");
          htmlDocument.RenderEndTag();
          htmlDocument.RenderEndTag();
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Body);
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Table);
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Tbody);
          htmlDocument.RenderBeginTag(HtmlTextWriterTag.Tr);
          // show form fields display name in table column
          string exportRestriction = FormRegistryUtil.GetExportRestriction(form.ID.ToString(), string.Empty);
          if (exportRestriction.IndexOf("created") == -1)
          {
             htmlDocument.RenderBeginTag(HtmlTextWriterTag.Th);
             htmlDocument.Write("Created");
             htmlDocument.RenderEndTag();
          }
         // Reading form fields and adding into table column
         FieldItem[] fields = form.Fields;
         for (int i = 0; i < fields.Length; i++)
         {

            FieldItem fieldItem = fields[i];
            if (exportRestriction.IndexOf(fieldItem.ID.ToString()) == -1)
            {
                htmlDocument.RenderBeginTag(HtmlTextWriterTag.Th);
                htmlDocument.Write(fieldItem.FieldDisplayName);
                htmlDocument.RenderEndTag();
            }
         }
         htmlDocument.RenderEndTag();

        // Create dynamic rows in table and adding WFFM form data in these rows
        foreach (IForm current in Packet.Entries)
        {
           htmlDocument.RenderBeginTag(HtmlTextWriterTag.Tr);
           string exportRestrictionForBody = FormRegistryUtil.GetE           xportRestriction(form.ID.ToString(), string.Empty);
          // Adding value of created field (default field)
           if (exportRestriction.IndexOf("Created") == -1)
            {
               htmlDocument.RenderBeginTag(HtmlTextWriterTag.Td);
               htmlDocument.Write(current.Timestamp.ToLocalTime().ToString("G"));
               htmlDocument.RenderEndTag();
            }
            FieldItem[] fields1 = form.Fields;
            FieldItem field;
            for (int i = 0; i < fields.Length; i++)
            {
               field = fields[i];
               if (exportRestriction.IndexOf(field.ID.ToString()) == -1)
               {
                   // Creating table row and adding form data
                   IField field2 = current.Field.FirstOrDefault((IField f) => f.FieldId == field.ID.Guid);
                   htmlDocument.RenderBeginTag(HtmlTextWriterTag.Td);
                   if (field2!=null && !string.IsNullOrEmpty(field2.Value))
                   {
                        htmlDocument.Write(field2.Value);
                   }
                   else
                   {
                        htmlDocument.Write(String.Empty);
                   }
                   htmlDocument.RenderEndTag();
                }
            }
            htmlDocument.RenderEndTag();
        }
        htmlDocument.RenderEndTag();
        htmlDocument.RenderEndTag();
        htmlDocument.RenderEndTag();
        htmlDocument.RenderEndTag();
        return stringWriter.ToString();
    }
}

After that another class to write logic of download/open form report in HTML:

This class contains complete code to generate HTML page with form data.


public static void ExportToHTMLFile(string formID, string filename)
{
     ItemUri uri = new ItemUri(Sitecore.Data.ID.Parse(formID), Sitecore.Context.Database);

    //1. Get Form
     FormItem form = new FormItem(Database.GetItem(uri));
     string name = form.FormName;

    //2. Data Filters
     List<GridFilter> filters = new List<GridFilter>();
     // 2.a Form filter
     //filters.Add(new GridFilter(Sitecore.Form.Core.Configuration.Constants.DataKey, formID, GridFilter.FilterOperator.Contains));
     // 2.b Get archived items
     //filters.Add(new GridFilter(Sitecore.Form.Core.Configuration.Constants.StorageName, Sitecore.Form.Core.Configuration.Constants.Archive, GridFilter.FilterOperator.Contains));

    filters.Add(new GridFilter("storageName", string.Empty, GridFilter.FilterOperator.Contains));
    filters.Add(new GridFilter("dataKey", formID, GridFilter.FilterOperator.Contains));

    //3. Get all entries
     IEnumerable<IForm> entries = Sitecore.Forms.Data.DataManager.GetForms().GetPage(new PageCriteria(0, 0x7ffffffe), null, filters);

    // 3.a Apply custom filtering on the entries
    //entries = entries.Where(a => a.Timestamp.Date.CompareTo(startDate) >= 0 && a.Timestamp.Date.CompareTo(endDate) <= 0);

    //4. Create a form packet
     FormPacket packet = new FormPacket(entries);

    CustomExportToHTML export = new CustomExportToHTML();
    string result = export.Process(form, packet);

    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".html");
    HttpContext.Current.Response.ContentType ="text/html";
    HttpContext.Current.Response.Write(result);
    HttpContext.Current.Response.End();
}

And at last I created a web form (formreports.aspx) page to show all forms of our website and generate HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">;
<head runat="server>;

 <title></title>;
 <style type="text/css">
        .ddl-forms {
            padding: 5px 0;
            font-size: 16px;
        }

        .txt-output {
            font-size: 16px;
            padding: 3px 5px;
        }

        .btn-submit {
            font-size: 16px;
            width:88%;
            height:40px;
            
        }
        .left{
            padding-left:90px;
        }
        .clear {
            clear:both;
        }
        .bottom {
            margin-top:15px;
        }
        .error {
            font-size: 16px;
            color:red;
            display:none;
            margin-top:5px;
            font-weight:bold;
        }
        .download-html {
            margin-top:10px;
        }
 </style>
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>;
</head>;
<body>
   <form id="form1" runat="server">;
      <div class="container" style="width: 980px; margin: 0 auto; font-size: 14px;">
        <fieldset class="title" style="padding-bottom:35px;">
        <legend><b>Download Web Form For Marketers Report</b></legend>
         

            <div class="left" style="width: 40%; text-align: center; float: left; min-height: 315px; padding-right: 20px;">
                 <fieldset class="title" style="min-height: 315px; padding: 10px 20px;">
                      <legend><b>Select Form</b></legend>
                        

                       <asp:DropDownList ID="ddlForms" Width="100%" Height="30px" CssClass="ddl-forms" runat="server" AutoPostBack="false">
                       <asp:ListItem Value="0">Select Form</asp:ListItem>                       </asp:DropDownList>
                      <br class="clearfix">
                  </fieldset>
              </div>
              <div class="right" style="float: left; width: 40%">
                   <fieldset class="title" style="min-height: 140px; text-align: center;">
                        <legend><b>Output File Name</b></legend>
                        

                        <asp:TextBox ID="txtOutputFileName" Width="88%" Height="28px" CssClass="txt-output" runat="server"></asp:TextBox>
                    </fieldset>
                    <div class="bottom">
                        <fieldset class="title" style="min-height: 140px; text-align:center;">
                            <legend><b>Download Reports</b></legend>
                            

                             <asp:Button ID="btnHTMLDownload" CssClass="btn-submit download-html" Text="Download HTML" runat="server" OnClick="btnHTMLDownload_Click" />
                            <asp:Panel ID="pnlError" runat="server" CssClass="error">
                                Please select any form
                            </asp:Panel>
                        </fieldset>
                    </div>
                </div>
                <div class="clear"></div>
            </fieldset>
        </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.btn-submit').click(function (e) {
                if ($('.ddl-forms').val() == "0") {
                    e.preventDefault();
                    $('.error').show();
                }
                else {
                    $('.error').hide();
                }
            });
        });
    </script>
</body>
</html>

In .cs file (formreport.aspx.cs) of above page I have written below code.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         var wffmFolderItem = Sitecore.Context.Database.GetItem("/sitecore/system/Modules/Web Forms for Marketers");
         if (wffmFolderItem != null)
         {
             var forms = wffmFolderItem.Axes.GetDescendants().Where(i => i.TemplateID.ToString() == "{FFB1DA32-2764-47DB-83B0-95B843546A7E}");
              foreach (FormItem itm in forms)
              {
                   ddlForms.Items.Add(new ListItem(itm.DisplayName, itm.ID.ToString()));
              }
              ddlForms.DataBind();
          }
     }
}
protected void btnHTMLDownload_Click(object sender, EventArgs e)
{
     try
     {
         if (ddlForms.SelectedValue.ToString() != "0")
         {
             pnlError.Visible = false;
             string formID = ddlForms.SelectedValue.ToString();
             string fileName = ddlForms.SelectedItem.Text.Replace(" ", "-") + "-formreport";
             if (!string.IsNullOrEmpty(txtOutputFileName.Text))
             {
                 fileName = txtOutputFileName.Text.Replace(".", "_");
             }
             ExportToExcelCommon.ExportToHTMLFile(formID, fileName);
         }
    }
    catch (Exception ex)
    {
        Sitecore.Diagnostics.Log.Error("Error in Custom Export To HTML", ex, this);
    }
}

Please see below screenshot how it’s working on front end.

WFFM-Page-View

 

How reports will show on front end –

WFFmM-Form-Reports

 

I will write another blog to export form data into XML format from front end.

Advertisements
This entry was posted in Sitecore and tagged , , , , , , . Bookmark the permalink.

4 Responses to Display Web Forms for Marketers Form Submissions Outside of the Form Reports

  1. Nice one.
    When adding a document upload to the webform and pulling a report, the uploaded documents are shown as a reference ID. The end user that needs to retrieve these documents for further handling has no direct access to these documents as they are stored in the database. Is there any way of including user friendly download link the exported file or even in the report viewer?

  2. Thanks John,

    With help of reference ID we can get media item and provide a link to download media item.
    I’ll update code to add download link for media items in report.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s