Umbraco Forms custom fieldtype

  • Monday, August 17, 2015 10:20 PM EST
  • Last Edited: Thursday, August 27, 2015 12:21 AM EST

1. Class to be placed in App_Code or in a compiled source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;

namespace CustomFormFields
{
    public class CheckboxPolicy : Umbraco.Forms.Core.FieldType
    {
        public CheckboxPolicy()
        {
            this.Id = new Guid("5C754DCE-8E85-4C7A-9CD6-B35441D44691");
            this.Name = "Checkbox Policy"; //this will also be the name of the view
            this.Description = "A checkbox for policy";
            this.Icon = "icon-checkbox";
            this.DataType = FieldDataType.String;
        }
        //extra settings
        [Umbraco.Forms.Core.Attributes.Setting("Policy", prevalues = "", description = "Enter the policy to show in the checkbox", view = "TextField")]
        public string Policy { get; set; }
        //custom value
        public override IEnumerable<object> ProcessSubmittedValue(Field field, IEnumerable<object> postedValues, HttpContextBase context)
        {
            List<object> returnValue = new List<object>();
            if (postedValues.ToList().Count > 0)
            {
                returnValue.Add("true");
            }
            else
            {
                returnValue.Add("false");
            }
            return returnValue;

        }
    }
}

 

2. Create html file that will show in the back office. This is to saved in App_Plugins\UmbracoForms\Backoffice\Common\FieldTypes

<input tabindex="-1" type="checkbox"/>
<textarea
		class="inline-editor inline-textarea fieldset-policy"
		select-on-focus
		umb-forms-auto-size
		ng-model="field.settings.Policy"
		placeholder="Write your policy to show in your checkbox here...">
</textarea>

 

3. create your view. this is to be placed in Views\Partials\Forms\Fieldtypes. The name has to be FieldType.[name of view defined in .cs code without spaces.cshtml. Example: FieldType.CheckboxPolicy

@model Umbraco.Forms.Mvc.Models.FieldViewModel    
@using Umbraco.Forms.Core.Extensions

@{
    var settings = Model.AdditionalSettings;
    var hasPolicy = (settings.ContainsKey("Policy") && !string.IsNullOrEmpty(settings["Policy"]));
}

<input type="checkbox" name="@Model.Name" id="@Model.Id" value="true" 
    @if(Model.Mandatory){<text>  data-val="true" data-val-requiredcb="@Model.RequiredErrorMessage"</text>}
	@if (Model.ContainsValue(true) || Model.ContainsValue("true") || Model.ContainsValue("on"))
    {<text>checked="checked"</text>}   
/>
@if (hasPolicy)
{
    <label for="@Model.Name">@settings["Policy"].ParsePlaceHolders()</label>
}

Sources:

https://our.umbraco.org/Documentation/Products/UmbracoForms/Developer/

 

comments powered by Disqus