Custom EPiServer Forms field
EPiServer recently released new add-on - EPiServer Forms. It is a new way how to work with the forms in EPiServer. Forms have different form elements available - Text (input), Text area, Number etc., but it misses basic label, heading and text elements to display static information for form users. Also, quite often there are requirements to provide additional information based on page's context - for example, on the product page, it might be required to post product code and name. This article describes basic steps to create custom EPiServer Forms field.
First of all, you have to install EPiServer Forms add-on into your project using NuGet:
Install-Package EPiServer.Forms
After installing it, you should be able to create forms in EPiServer's administrative interface.
Now create new form element type by creating a new class which inherits from ElementBlockBase and add ContentType attribute as for other content types. In the example below, I am creating new form element which has current page's name as a property.
[ContentType(GUID = "9AD6588C-A85A-4FD2-A20E-2B1778552648")]
public class PageNameFieldBlock : ElementBlockBase
{
public string PageName
{
get
{
var pageHandler = ServiceLocator.Current.GetInstance<PageRouteHelper>();
return pageHandler.Page.PageName;
}
}
}
If you require extending existing element, then you can inherit from existing element's type and implement your custom functionality.
Next step is defining the view. When using default Alloy Tech site's view engine, the view should be placed in the ~/Views/Shared/Blocks folder with the same name as field element's class name. For the PageNameFieldBlock element the view should be called PageNameFieldBlock.cshtml.
@model EPiFormsTesting.Models.PageNameFieldBlock
<h1>@Model.PageName</h1>
<input name="@Model.FormElement.Code" id="@Model.FormElement.Guid" type="hidden"
value="@Model.PageName"
class="Form__Element FormHidden FormHideInSummarized" @Html.Raw(Model.FormElement.AttributesString) />
Here I am displaying the page name and also creating a hidden element to post it. For EPiServer Forms to correctly handle form data, HTML element's name should have a value of the model property FormElement.Code and HTML element's id should have a value of the model property FormElement.Guid. Also, you should render additional attributes from the model property FormElement.AttributesString. You can find more examples in the _~/modules/protected/EPiServer.Forms/Views/Blocks folder. The views in this folder are .ascx files but are quite easy to understand and translate to Razor files.
Now the new field element should be available when creating new forms. I have created sample form with several fields including a field from a newly created element.
After posting the form, posted page name appears in form submissions.