Kentico CMS 7.0 Developer's Guide

Developing form controls

Developing form controls

Previous topic Next topic Mail us feedback on this topic!  

Developing form controls

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

The following example shows how to create a form control that will allow users to choose a color from a drop-down list. The example is relatively simple, but the same basic approach can be used to create any type of custom form control or modify an existing one.

 

1. Open your web project in Visual Studio (or Visual Web Developer) using the WebProject.sln file or via File -> Open -> Web site in Visual Studio.
 

2. Right-click the CMSFormControls folder and choose Add New Item. Choose to create a new Web User Control and call it ColorSelector.ascx.
 

devguide_clip0169
 

This folder (or a sub‑folder under it) should always be used to store the source files of custom form controls, since it ensures that registered form controls are exported correctly along with the site.

 

3. Edit the new control on the Design tab. Drag and drop a standard DropDownList control onto the form from the Toolbox:
 
devguide_clip0170
 
4. Edit the properties of the DropDownList and change its ID to drpColor.
 

5. Switch to the code behind and add a reference to the following namespace:

 
[C#]
 

using CMS.FormControls;
using CMS.GlobalHelper;

 

[VB.NET]

 

Imports CMS.FormControls
Imports CMS.GlobalHelper

 

6. Next, modify the class definition according to the following:

 

[C#]

 

public partial class CMSFormControls_ColorSelector : System.Web.UI.UserControl

 

to

 

public partial class CMSFormControls_ColorSelector : FormEngineUserControl

 

[VB.NET]

 

Partial Class CMSFormControls_ColorSelector
  Inherits System.Web.UI.UserControl

 

to

 
Partial Class CMSFormControls_ColorSelector
  Inherits FormEngineUserControl

 

This ensures that our form control inherits from the CMS.FormControls.FormEngineUserControl class and can use its standard properties.
 

7. Now add the following members into the class:
 

[C#]

 

/// <summary>
/// Gets or sets the value entered into the field, a hexadecimal color code in this case.
/// </summary>

public override Object Value
{
    get
    {
        return drpColor.SelectedValue;
    }
    set
    {
        // Ensure drop down list options
        EnsureItems();
        drpColor.SelectedValue = System.Convert.ToString(value);
    }
}
 
/// <summary>
/// Property used to access the Width parameter of the form control.
/// </summary>
public int SelectorWidth
{
    get
    {
        return ValidationHelper.GetInteger(GetValue("SelectorWidth"), 0);
    }
    set
    {
        SetValue("SelectorWidth"value);
    }
}
 
/// <summary>

/// Returns an array of values of any other fields returned by the control.

/// </summary>

/// <returns>It returns an array where the first dimension is the attribute name and the second is its value.</returns>

public override object[,] GetOtherValues()
{
    object[,] array = new object[1, 2];
    array[0, 0] = "ProductColor";
    array[0, 1] = drpColor.SelectedItem.Text;
    return array;
}

 
/// <summary>
/// Returns true if a color is selected. Otherwise, it returns false and displays an error message.
/// </summary>

public override bool IsValid()
{
    if ((string)Value != "")
    {
        return true;
    }
    else
    {
        // Set form control validation error message.
        this.ValidationError = "Please choose a color.";
        return false;
    }
}
 
 
/// <summary>
/// Sets up the internal DropDownList control.
/// </summary>
protected void EnsureItems()
{

  // Applies the width specified through the parameter of the form control if it is valid.

    if (SelectorWidth > 0)
    {
        drpColor.Width = SelectorWidth;
    }
 
    if (drpColor.Items.Count == 0)
    {
        drpColor.Items.Add(new ListItem("(select color)"""));
        drpColor.Items.Add(new ListItem("Red""#FF0000"));
        drpColor.Items.Add(new ListItem("Green""#00FF00"));
        drpColor.Items.Add(new ListItem("Blue""#0000FF"));        
    }    
}
 
/// <summary>
/// Handler for the Load event of the control.
/// </summary>

protected void Page_Load(object sender, EventArgs e)
{
    // Ensure drop-down list options
    EnsureItems();
}

 

[VB.NET]

 

''' <summary>
''' Gets or sets the value entered into the field, a hexadecimal color code in this case.
''' </summary>
Public Overrides Property Value() As Object
  Get
      Return drpColor.SelectedValue
  End Get
  Set(ByVal value As Object)
       EnsureItems()
       drpColor.SelectedValue = System.Convert.ToString(value)
  End Set
End Property
 
''' <summary>
''' Property used to access the Width parameter of the form control.
''' </summary>
Public Property SelectorWidth() As Integer
  Get
      Return ValidationHelper.GetInteger(GetValue("SelectorWidth"), 0)
  End Get
  Set(ByVal value As Integer)
       SetValue("SelectorWidth", value)
  End Set
End Property
 
''' <summary>

''' Sets values for any other fields (attributes) of the object in which the form control is used.

''' </summary>

''' <returns>Returns an array where the first dimension is the field's column name and the second is its value.</returns>

Public Overrides Function GetOtherValues() As Object(,)
    Dim arr(0, 1) As Object
    arr(0, 0) = "ProductColor"
    arr(0, 1) = drpColor.SelectedItem.Text
    Return arr
End Function

 
''' <summary>
''' Returns true if a color is selected. Otherwise, it returns false and displays an error message.
''' </summary>

Public Overrides Function IsValid() As Boolean
    If CType(Value, String) <> "" Then
        Return True
    Else
        ' Set form control validation error message.
        Me.ValidationError = "Please choose a color."
        Return False
    End If
End Function
 
 
''' <summary>
''' Sets up the internal DropDownList control.
''' </summary>
Public Sub EnsureItems()

  ' Applies the width specified through the parameter of the form control if it is valid.

    If SelectorWidth > 0 Then
        drpColor.Width = SelectorWidth
    End If
 
    If drpColor.Items.Count = 0 Then
        drpColor.Items.Add(New ListItem("(select color)"""))
        drpColor.Items.Add(New ListItem("Red""#FF0000"))
        drpColor.Items.Add(New ListItem("Green""#00FF00"))
        drpColor.Items.Add(New ListItem("Blue""#0000FF"))
    End If
End Sub
 
''' <summary>

''' Handler for the Load event of the control.

''' </summary>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ' Ensure drop down list options
    EnsureItems()
End Sub

 

The above code overrides three members inherited from the FormEngineUserControl class that are most commonly used when developing form controls:

 

Value - it is necessary to override this property for every form control. It is used to get and set the value of the field provided by the control.

GetOtherValues() - this method is used to set values for other fields of the object in which the form control is used. It must return a two dimensional array containing the names of the fields (columns) and their assigned values. Typically used for multi‑field form controls that need to store data in multiple database columns, but only occupy a single field in the form.

IsValid() - this method is used to implement validation for the values entered into the field. It must return true or false depending on the result of the validation.

 

Also notice that a SelectorWidth property was defined for the form control. It serves as a way to access the value of a parameter that will be defined for the form control later in the example. This property is used in the EnsureItems() method to set the width of the internal drop-down list .

 

Remember to save the changes to both code files and Build your project if it is installed as a web application.

 

8. Go to Site Manager -> Development -> Form controls where you can register the new form control in the system. Click the NewFormControl New form control button, select the Create a new form control option and enter the following values:

 

Display name: Custom color selector

Code name: Leave the (automatic) option

Type: Selector

File name: ~/CMSFormControls/ColorSelector.ascx (you can use the Select button to choose the file)

 

devguide_clip1701

 

Click Save Save and the form control will be created.

 
9. You will be redirected to the control's General tab. Here, check the Use control for - Text and Show control in - Document types boxes and click Save Save again.

 

devguide_clip0171

 

10. Switch to the Properties tab where parameters can be defined for the form control. Use the New attribute (AddWebPart) action and set the following values for the parameter:

 

Column name: SelectorWidth

Attribute type: Integer number

Allow empty value: true (checked)

 

Display attribute in editing form: true

 

Field caption: Drop-down list width

Form control: Text box

 

When finished, click Save Save.

 

devguide_clip0069

 

This parameter will allow users to specify the width of the color selector directly from the administration interface whenever they add this control to a form. The code of the form control already ensures that the value is properly applied.

 

11. Now we will test this control by placing it onto a document editing form. Go to Site Manager -> Development -> Document types and edit (Edit) the Product document type. Select the Fields tab to access the field editor for this document type. Add two new fields using the New attribute (AddWebPart) action. Set the following properties for the fields:

 

Column name: ProductColor

Attribute type: Text

Attribute size: 100

Display attribute in editing form: false

 

This field will store the name of the color selected for the product. It will not be available in the editing form, its value will be set automatically by the GetOtherValues() method of the ColorSelector.ascx control (notice that the Column name matches the name used in the code of the method).

 

Click Save Save and create the next field:

 

Column name: ProductHexaColor

Attribute type: Text

Attribute size: 100

Allow empty value: true (checked)

 

Display attribute in editing form: true

 

Field caption: Color

Form control: Custom color selector

 

This field will store the hexadecimal code of the selected color. In the code of the form control, this value is handled through the Value property. The field will be displayed in the document's editing form according to the design of the custom form control.

 

Notice that the Editing control settings section of this field contains the Drop-down list width field. This is the SelectorWidth parameter defined for the form control in the previous step. Try to specify the width of the selector by entering some number, for example 200.

 

Click Save Save again.

 

devguide_clip0373
 

12. Go to CMS Desk -> Content and create a new document of the Product document type under the Products section. For the purposes of this example, choose the Do not create an SKU option in the SKU binding section. The document's editing form will contain the new form control as shown below:
 

devguide_clip0374
 

As you can see, the document field can be managed using the custom form control. The width of the displayed drop-down list will match the value that you entered into the form control's parameter. If you do not choose any color, the validation error message defined in the code of the form control will be displayed.

 

By implementing custom form controls as shown in this example, it is possible to create editing forms with almost unlimited flexibility, both in the administration interface and on the live site.

 

 

 

Getting and setting values of other fields using the API

 

The data of the current form can be accessed through the Form property of the form control inherited from the FormEngineUserControl class.

 

You can retrieve the values entered into other fields using the following method:

 

Form.GetFieldValue(string columnName) - returns an object containing the value of the specified field.

 

For example, the following code could be used to get the value of the ProductName field from the current form (New product is returned if the field is empty):

 

[C#]

 

string productName = CMS.GlobalHelper.ValidationHelper.GetString(Form.GetFieldValue("ProductName"), "New product");

 

To set the value of a field, you can use the following approach:

 

Form.Data.SetValue(string columnName, object value) - sets a value for the specified field.

 

To modify the value of a field before the form is saved, you need to place the code inside the IsValid method of your form control.