Skip to content

Instantly share code, notes, and snippets.

Created February 12, 2014 10:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8953426 to your computer and use it in GitHub Desktop.
Save anonymous/8953426 to your computer and use it in GitHub Desktop.
Umbraco Contour Render Form Usercontrol sourcecode
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RenderForm.ascx.cs" Inherits="Umbraco.Forms.UI.Usercontrols.RenderForm" %>
<%@ Register Assembly="Umbraco.Forms.Core" Namespace="Umbraco.Forms.Core.Controls.Validation" TagPrefix="uform" %>
<asp:PlaceHolder ID="ph_noFormWarning" runat="server" Visible="false">
<div style="border: 2px solid red; padding: 10px; text-align: center; color: Red;">
Umbraco Contour will only work properly if placed inside a &lt;form runat="server"&gt; tag.
</div>
</asp:PlaceHolder>
<asp:PlaceHolder id="ph_styles" runat="server" />
<asp:PlaceHolder id="placeholder" runat="server" Visible="true">
<div id='contour' <asp:Literal ID="pageCssClass" runat="server" />>
<asp:Literal ID="pageName" runat="server" />
<asp:ValidationSummary ID="validationsummary" runat="server" Enabled="false" CssClass="contourValidationSummary"/>
<asp:Repeater ID="rpFieldsets" runat="server" OnItemDataBound="RenderFieldset">
<ItemTemplate>
<fieldset class='contourFieldSet <asp:Literal ID="cssClass" runat="server" />'>
<asp:Literal ID="legend" runat="server" />
<asp:Repeater id="rpFields" runat="server" OnItemDataBound="RenderField">
<ItemTemplate>
<div class='contourField <asp:Literal ID="cssClass" runat="server" />'>
<!-- Our label -->
<asp:Label ID="label" CssClass="fieldLabel" runat="server"/>
<div>
<!-- The data entry control -->
<asp:PlaceHolder ID="placeholder" runat="server" />
</div>
<!-- Our Tooltip -->
<asp:Literal ID="tooltip" runat="server" />
<!-- Validation -->
<uform:RequiredValidator ID="mandatory" runat="server" ErrorMessage="mandatory" Visible="false" Display="Dynamic" CssClass="contourError" />
<uform:RegexValidator ID="regex" ErrorMessage="The field could not be validated" runat="server" Visible="false" Display="Dynamic" CssClass="contourError" />
<br style="clear: both;" />
</div>
</ItemTemplate>
</asp:Repeater>
</fieldset>
</ItemTemplate>
</asp:Repeater>
<div class="contourNavigation">
<asp:Button ID="b_prev" runat="server" OnClick="prevPage" CssClass="contourButton contourPrev" Text="Previous"/>
<asp:Button ID="b_next" runat="server" OnClick="nextPage" CssClass="contourButton contourNext" Text="Next"/>
</div>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="ph_messageOnSubmit" runat="server" Visible="false">
<p class="contourMessageOnSubmit">
<asp:Literal ID="lt_message" runat="server" />
</p>
</asp:PlaceHolder>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Umbraco.Forms.Core;
using System.Text.RegularExpressions;
using Umbraco.Forms.Core.Extensions;
using Umbraco.Forms.Data.Storage;
using System.Collections.Generic;
using Umbraco.Forms.Core.Services;
using Umbraco.Forms.Core.Enums;
using Umbraco.Forms.Core.Controls.Validation;
using Umbraco.Forms.Core.Providers;
namespace Umbraco.Forms.UI.Usercontrols
{
public partial class RenderForm : System.Web.UI.UserControl
{
public string FormGuid { get; set; }
private bool m_allowEditing = false;
//optional properties, these can be enabled but is not in the macro setup by default
public bool AllowEditing { get { return m_allowEditing; } set { m_allowEditing = value; } }
public string SubmitButtonText { get; set; }
public string NextButtonText { get; set; }
public string PreviousButtonText { get; set; }
public string PageNameTag { get; set; }
private Guid sessionKey;
private List<Field> currentFields = new List<Field>();
private string formSessionKey;
private Umbraco.Forms.Core.Services.RecordService formService;
protected void RenderField(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
Field f = (Field)e.Item.DataItem;
FieldType ft = f.FieldType;
ft.AssociatedField = f;
ft.Rendered = true;
if(ft.SupportsPrevalues && f.PreValueSource != null){
f.PreValueSource.Type.LoadSettings(f.PreValueSource);
}
Label _label = (Label)e.Item.FindControl("label");
Literal _tooltip = (Literal)e.Item.FindControl("tooltip");
Literal _cssClass = (Literal)e.Item.FindControl("cssClass");
PlaceHolder _placeholder = (PlaceHolder)e.Item.FindControl("placeholder");
RequiredValidator _mandatory = (RequiredValidator)e.Item.FindControl("mandatory");
_mandatory.LabelControlToValidate = _label.ID;
RegexValidator _regex = (RegexValidator)e.Item.FindControl("regex");
_regex.LabelControlToValidate = _label.ID;
if (f.FieldType.HideLabel)
_label.Visible = false;
else
{
_label.Text = f.Caption.ParsePlaceHolders();
if (f.Mandatory && formService.Form.FieldIndicationType == FormFieldIndication.MarkMandatoryFields)
_label.Text += " <span class=\"contourIndicator\">" + dictionary(formService.Form.Indicator) + "</span>";
if (!f.Mandatory && formService.Form.FieldIndicationType == FormFieldIndication.MarkOptionalFields)
_label.Text += " <span class=\"contourIndicator\">" + dictionary(formService.Form.Indicator) + "</span>";
}
if(f.ToolTip.Length > 0)
_tooltip.Text = "<small>" + dictionary(f.ToolTip) + "</small>";
if (f.Values.Count > 0)
ft.Values = f.Values;
WebControl wf = ft.Editor;
wf.ID = f.Id.ToString().Replace("-","_");
if (f.FieldType.HideField)
wf.Visible = false;
_placeholder.Controls.Add(wf);
_label.AssociatedControlID = wf.ID;
if (f.Mandatory && !f.FieldType.HideField)
{
_mandatory.ValidationGroup = ClientID;
_mandatory.ControlToValidate = wf.ID;
_mandatory.Visible = true;
//if (ScriptManager.GetCurrent(this.Page) != null)
//{
// //ValidationFieldExtender _mandatoryextender = new ValidationFieldExtender();
// //_mandatoryextender.InvalidLabelCssClass = "contourError";
// //_mandatoryextender.InvalidTextBoxCssClass = "contourError";
// //_mandatoryextender.ValidLabelCssClass = "contourValid";
// //_mandatoryextender.ValidTextBoxCssClass = "contourValid";
// //_mandatoryextender.TargetLabelID = _label.ID;
// //_mandatoryextender.TargetControlID = _mandatory.ID;
// //_placeholder.Controls.Add(_mandatoryextender);
//}
string mandatoryErrorMessage = formService.Form.RequiredErrorMessage;
if (!string.IsNullOrEmpty(f.RequiredErrorMessage))
mandatoryErrorMessage = f.RequiredErrorMessage;
_mandatory.ErrorMessage = string.Format(dictionary(mandatoryErrorMessage), dictionary(f.Caption));
if (formService.Form.HideFieldValidation)
_mandatory.Display = ValidatorDisplay.None;
}
if (!string.IsNullOrEmpty(f.RegEx) && !f.FieldType.HideField)
{
_regex.ValidationGroup = ClientID;
_regex.ControlToValidate = wf.ID;
_regex.ValidationExpression = dictionary(f.RegEx);
_regex.Visible = true;
//if (ScriptManager.GetCurrent(this.Page) != null)
//{
// ValidationFieldExtender _regexextender = new ValidationFieldExtender();
// _regexextender.InvalidLabelCssClass = "contourError";
// _regexextender.InvalidTextBoxCssClass = "contourError";
// _regexextender.ValidLabelCssClass = "contourValid";
// _regexextender.ValidTextBoxCssClass = "contourValid";
// _regexextender.TargetLabelID = _label.ID;
// _regexextender.TargetControlID = _regex.ID;
// _placeholder.Controls.Add(_regexextender);
//}
string validationMessage = formService.Form.InvalidErrorMessage;
if (!string.IsNullOrEmpty(f.InvalidErrorMessage))
validationMessage = f.InvalidErrorMessage;
_regex.ErrorMessage = string.Format(dictionary(validationMessage), dictionary(f.Caption));
if (formService.Form.HideFieldValidation)
_regex.Display = ValidatorDisplay.None;
}
_cssClass.Text = wf.CssClass + " " + Umbraco.Forms.Data.XmlHelper.XmlName(f.Caption) + " " + Umbraco.Forms.Data.XmlHelper.XmlName(ft.GetType().Name);
if (f.Mandatory)
_cssClass.Text += " mandatory";
if (!string.IsNullOrEmpty(f.RegEx))
_cssClass.Text += " hasvalidator";
bool isFieldEven = ((e.Item.ItemIndex % 2) == 0);
if(!isFieldEven)
_cssClass.Text += " alternating";
}
}
protected void RenderFieldset(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
FieldSet fs = (FieldSet)e.Item.DataItem;
Literal _legend = (Literal)e.Item.FindControl("legend");
Literal _cssClass = (Literal)e.Item.FindControl("cssClass");
Repeater _rpFields = (Repeater)e.Item.FindControl("rpFields");
if (fs.Caption.Length > 0)
{
_legend.Text = "<legend>" + fs.Caption.ParsePlaceHolders() + "</legend>";
_cssClass.Text = Data.XmlHelper.XmlName(fs.Caption);
}
_rpFields.DataSource = fs.Fields;
_rpFields.DataBind();
}
}
protected void nextPage(object sender, EventArgs e)
{
Page.Validate(ClientID);
if (Page.IsValid)
{
//formService.SaveRecord();
formService.NextPage();
RenderUi();
}
}
protected void prevPage(object sender, EventArgs e)
{
//formService.SaveRecord();
formService.PreviousPage();
RenderUi();
}
private bool hasForm()
{
Control t = this;
while (t != null)
{
if (t.GetType() == typeof(System.Web.UI.HtmlControls.HtmlForm))
return true;
if (t.Parent == null)
break;
t = t.Parent;
}
return false;
}
protected override void OnInit(EventArgs e)
{
if (!hasForm())
{
ph_noFormWarning.Visible = true;
}
else
{
//if (umbraco.presentation.UmbracoContext.Current == null || !umbraco.presentation.UmbracoContext.Current.PageId.HasValue)
//{
// if (umbraco.cms.businesslogic.language.Language.getAll.Count() > 0)
// {
// this.Page.UICulture = umbraco.cms.businesslogic.language.Language.getAll[0].CultureAlias;
// this.Page.Culture = umbraco.cms.businesslogic.language.Language.getAll[0].CultureAlias;
// }
//}
if (ScriptManager.GetCurrent(this.Page) == null)
{
ScriptManager sManager = new ScriptManager();
placeholder.Controls.Add(sManager);
}
if (!string.IsNullOrEmpty(FormGuid))
{
GetCurrentService();
RenderUi();
}
else
{
placeholder.Visible = false;
}
}
}
void RecordService_RecordApproved(object sender, RecordEventArgs e)
{
RecordService rs = new RecordService(e.Record);
rs.Delete();
rs.Dispose();
}
private void RenderUi()
{
bool render = true;
bool error = false;
if (formService != null)
{
switch (formService.Record.State)
{
case FormState.Approved:
case FormState.Submitted:
case FormState.Deleted:
render = false;
break;
default:
break;
}
//Response.Write(formService.EditMode.ToString());
if (render)
{
if (!formService.Form.DisableDefaultStylesheet)
{
HtmlLink cssLink = new HtmlLink();
cssLink.Href = umbraco.GlobalSettings.Path + "/plugins/umbracoContour/css/defaultform.css";
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
if (Page.Header != null)
{
Page.Header.Controls.Add(cssLink);
}
else
{
ph_styles.Controls.Add(cssLink);
}
}
if (formService.Form.ShowValidationSummary)
{
validationsummary.Enabled = true;
validationsummary.ValidationGroup = ClientID;
}
string _submitTxt = SubmitButtonText ?? capitalizeFirst(dictionary("#submit"));
string _nextTxt = NextButtonText ?? capitalizeFirst(dictionary("#next"));
string _prevTxt = PreviousButtonText ?? capitalizeFirst(dictionary("#prev"));
if (formService.OnLastPage)
{
b_next.Text = _submitTxt;
b_next.CssClass = "contourButton contourNext contourSubmit";
}
else
{
b_next.Text = _nextTxt;
b_next.CssClass = "contourButton contourNext";
}
b_prev.Text = _prevTxt;
b_prev.Visible = !formService.OnFirstPage;
b_next.ValidationGroup = ClientID;
placeholder.Visible = true;
if (formService.CurrentPage.Caption.Length > 0)
{
pageName.Text = string.Format("<{0} class='contourPageName'>{1}</{0}>",
string.IsNullOrEmpty(PageNameTag) ? "h4" : PageNameTag,
formService.CurrentPage.Caption.ParsePlaceHolders());
}
else
pageName.Text = "";
pageCssClass.Text = "class=\"" + Data.XmlHelper.XmlName(formService.Form.Name) + " " + Data.XmlHelper.XmlName(formService.CurrentPage.Caption) + "\"";
rpFieldsets.DataSource = formService.CurrentPage.FieldSets;
rpFieldsets.DataBind();
ph_messageOnSubmit.Visible = false;
if (formService.Record.Id != Guid.Empty)
{
HttpCookie cook = new HttpCookie(formSessionKey);
cook.Expires = DateTime.Now.AddHours(1);
cook.Value = formService.Record.Id.ToString();
}
}
else if (!error)
{
int GotoPageOnSubmit = formService.Form.GoToPageOnSubmit;
string MessageOnSubmit = Umbraco.Forms.Data.StringHelper.ParsePlaceHolders(HttpContext.Current, formService.Record, formService.Form.MessageOnSubmit);// dictionary(formService.Form.MessageOnSubmit);
string XPathOnSubmit = formService.Form.XPathOnSubmit;
Session.Remove(formService.Record.Id.ToString() +"_editMode");
string recordid = formService.Record.Id.ToString();
formService = null;
if (formSessionKey != null)
{
Response.Cookies[formSessionKey].Value = null;
Response.Cookies[formSessionKey].Expires = DateTime.Now.AddDays(-1);
}
if (GotoPageOnSubmit > 0)
Response.Redirect(umbraco.library.NiceUrl(GotoPageOnSubmit) + "?recordid=" + recordid);
else if (!string.IsNullOrEmpty(XPathOnSubmit) && umbraco.presentation.UmbracoContext.Current.PageId != null)
Response.Redirect(umbraco.library.NiceUrl(Convert.ToInt32(Umbraco.Forms.Data.XpathExecutionHelper.GetResult(XPathOnSubmit))) + "?recordid=" + recordid);
else
{
placeholder.Visible = false;
ph_messageOnSubmit.Visible = true;
if (!string.IsNullOrEmpty(MessageOnSubmit) && !MessageOnSubmit.Contains('<') && !MessageOnSubmit.Contains('>'))
MessageOnSubmit = umbraco.library.ReplaceLineBreaks(MessageOnSubmit);
lt_message.Text = MessageOnSubmit;
}
}
}
}
private string capitalizeFirst(string word)
{
if (word.Length > 1)
{
return char.ToUpper(word[0]) + word.Substring(1);
}
else
{
return word.ToUpper();
}
}
public void GetCurrentService() {
FormStorage fs = new FormStorage();
Guid g;
Form form = null;
if (Umbraco.Forms.Data.GuidHelper.GuidTryParse(FormGuid, out g))
{
form = fs.GetForm(new Guid(FormGuid));
}
else
{
//fetch by name, handy when working with multiple envirmonments and id isn't the same
form = fs.GetForm(FormGuid);
}
fs.Dispose();
if (form == null || form.Id == Guid.Empty) {
Literal error = new Literal();
error.Text = "<div class='contourErrorMessage'>Form could not be loaded, form is either missing or damaged</div>";
ph_styles.Controls.Add(error);
placeholder.Visible = false;
} else {
formSessionKey = RecordService.GetCookieReference(form);
string _cookie = umbraco.library.RequestCookies(formSessionKey);
string _recordGuid = umbraco.library.RequestQueryString("recordGuid");
if (!string.IsNullOrEmpty(_cookie) && Umbraco.Forms.Data.GuidHelper.GuidTryParse(_cookie, out sessionKey)) {
//so we fetch whatever data is currently there...
RecordStorage rs = new RecordStorage();
Record record = rs.GetRecord(sessionKey);
rs.Dispose();
//Response.Write("from cookie");
formService = new Umbraco.Forms.Core.Services.RecordService(form, record);
if (Session[record.Id.ToString() + "_editMode"] != null)
if ( (bool)Session[record.Id.ToString() + "_editMode"] == true )
formService.EditMode = true;
formService.Resume();
}else if(m_allowEditing && !string.IsNullOrEmpty(_recordGuid) ){
RecordStorage rs = new RecordStorage();
Record record = rs.GetRecord(new Guid(_recordGuid));
rs.Dispose();
formService = new Umbraco.Forms.Core.Services.RecordService(form, record);
formService.EditMode = true;
Session[record.Id.ToString() + "_editMode"] = true;
formService.Resume(0);
} else {
//Response.Write("new service");
formService = new Umbraco.Forms.Core.Services.RecordService(form);
formService.Open();
}
}
}
private static string dictionary(string text) {
return Umbraco.Forms.Data.DictionaryHelper.GetText(text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment