17 May 2014

WFFM custom field with Placeholder


Here is a simple entry on this blog, but I wanted to add it here to show how simple it is to create or extend fields in WFFM.

On a recent project we ad this form where the text fields did not have labels. Instead, the text was placed on the TextBox. Basically something like the below image:



Obviously you could add it as Default Value and get some JS to clear the field on focus... But a nicer way to do this is to ensure the text is placed on the placeholder attribute:

< input class="scfSingleLineTextBox" id="uc_2_form_ED630308419A4EB9A4D237E767A70A2A_field_D553FA1A5DF1403BA2A732D45CD4298D" maxlength="256" name="uc_2$form_ED630308419A4EB9A4D237E767A70A2A$field_D553FA1A5DF1403BA2A732D45CD4298D" placeholder="First Name" type="text" />


If you go into the form editor in sitecore, unfortunately you will not have the placeholder attribute on the default fields: Single Line, Email...

So, lets create a custom field:

1- Create an item in Sitecore for your custom Field

2- Create a class on your project as per the following

using Oakton.Business.Interfaces.Wffm;
using Sitecore.Form.Core.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using ScWffm = Sitecore.Form;

namespace MyProject.Sitecore.Wffm
{
    [ValidationProperty("Text")]
    public class SingleLineText : ScWffm.Web.UI.Controls.SingleLineText, IPlaceholderField
    {
        [VisualCategory("Custom Properties")]
        [VisualProperty("Placeholder Text", 2)]
        [DefaultValue("")]
        public string PlaceholderText { get; set; }

        protected override void OnInit(EventArgs e)
        {
            if (!String.IsNullOrEmpty(PlaceholderText))
            {
                textbox.Attributes["placeholder"] = PlaceholderText;
            }

            base.OnInit(e);
        }
    }
}


From the above code, you can see that the class will inherit from the SingleLineText and extend it to include a PlaceholderText Property. This property will be visible on the WFFM edit form. Then render as placeholder attribute on the frontend...

When editing the form you will now be able to select the new field:



Then you will see the new property on the left hand side:

 Don't forget to publish the fields and form and there you have a custom field in WFFM...

2 comments:

  1. Hi how can you remove the legend title on wffm. I am just using wffm, they have a structure legend:input textbox, but i just want the same like you with just textbox. Where should i change it?

    I appreciate your help T_T

    ReplyDelete
  2. This concept is a good way to enhance the knowledge.thanks for sharing..
    Sitecore Training
    Sitecore Online Training
    Sitecore Training in Hyderabad

    ReplyDelete