Defining field visibility conditions

Field visibility conditions allow you to restrict whether form fields are displayed.

Natively, the system provides visibility conditions that set field visibility based on the value of a different field in the form. For example, you can configure fields to display only to users above a certain age threshold (a value they provided somewhere else in the form). In addition, the form builder framework allows you to define custom conditions suitable for your exact use cases and scenarios.

Behavior of fields hidden by visibility conditions

When a field’s visibility condition is false, it is not rendered anywhere in the form’s output code – there is no hidden input.

If a field’s visibility condition is true when the form is initially displayed, but later becomes false before the form is submitted, any data entered into the field is not recorded. The form data instead saves the field’s default value.

A visibility condition consists of logic that evaluates whether a given field is displayed – implemented in the condition’s IsVisible method – and, optionally, a set of properties providing a configuration interface for the condition (located on a field’s Form builder -> Visibility tab).

The system allows you to define the following types of visibility conditions:

  • Basic visibility conditions – can contain arbitrary logic to determine a field’s visibility.
  • Depending visibility conditions – conditions that depend on other fields in the form. These conditions are strongly typed – a condition defined for decimalvalue types can only be applied to fields that use form components handling values of the corresponding data type.

MVC Areas

Form components are designed to be used in the global scope and therefore must be registered in the application root of your live site project (not in an MVC Area). Registering form components in MVC Areas may lead to unexpected behavior.

Areas

Form sections are designed to be used in the global scope and their code files must be placed in the application root of your Core project (not in an Area). Creating sections in Areas may lead to unexpected behavior.

Defining basic visibility conditions

Basic visibility conditions usually work with contextual data available for each user (contact) in the system, such as their persona, contact group, or the email feed to which they subscribe. All basic visibility conditions inherit from the VisibilityCondition base class.

To define a basic visibility condition:

  1. Open your live site project in Visual Studio.

  2. Create a new class that inherits from the VisibilityCondition base class (available in the Kentico.Forms.Web.Mvc namespace).

  3. Annotate the class with the Serializable attribute.

  4. (Optional) In case of more complex visibility conditions, define custom properties and annotate them with the EditingComponent attribute to provide a configuration interface for users.

    
    
    
             // Defines a configuration interface for the condition
             // The 'EditingComponent' attribute specifies which form component is used as the property's value editor
             [EditingComponent(TextInputComponent.IDENTIFIER)]
             public string ConfigurableProperty { get; set; }
    
    
    
     
  5. Override the following method:

    • IsVisible– contains logic that determines a field’s visibility. The method needs to return either true – the field is displayed, or false– the field remains hidden.
    
    
    
             // Contains custom visibility logic evaluated by the server
             // True indicates the field is displayed, false indicates the field is hidden
             public override bool IsVisible()
             {
                 return true;
             }
    
    
    
     
  6. Register the visibility condition in the system.

  7. Build the project.

The visibility condition is now registered in the system and ready to be applied to form fields via the Form builder interface.

Example - Defining a basic visibility condition

The following example demonstrates the implementation of a visibility condition that checks if the user viewing the form is in a given persona and displays the field accordingly:




using System;

using CMS.ContactManagement;
using CMS.Personas;

using Kentico.Forms.Web.Mvc;

using LearningKit.FormBuilder.CustomVisibilityConditions;

// Registers the visibility condition in the system
[assembly: RegisterFormVisibilityCondition("IsInPersonaVisibilityCondition", typeof(IsInPersonaVisibilityCondition), "User is in persona")]

namespace LearningKit.FormBuilder.CustomVisibilityConditions
{
    [Serializable]
    // A visibility condition that checks whether a user is in the specified persona
    public class IsInPersonaVisibilityCondition : VisibilityCondition
    {
        // Defines a configuration interface for the visibility condition
        // The 'EditingComponent' attribute specifies which form component is used as the property's value editor
        [EditingComponent(TextInputComponent.IDENTIFIER, Label = "Required persona")]
        public string RequiredPersona { get; set; }

        // Checks whether the current user belongs to the specified persona
        // Called when the visibility condition is evaluated by the server
        public override bool IsVisible()
        {
            ContactInfo currentContact = ContactManagementContext.GetCurrentContact();

            string currentPersonaName = currentContact?.GetPersona()?.PersonaName;

            return String.Equals(currentPersonaName, RequiredPersona, StringComparison.InvariantCultureIgnoreCase);
        }
    }
}


The visibility condition is now available on the Form builder -> Visibility tab of form fields.

Configuring the implemented visibility condition

Defining depending visibility conditions

This type of visibility conditions allows you to display additional form fields based on information users provided elsewhere in the form. For example, if field X1  contains value Y, field X2  becomes visible. All visibility conditions of this type need to inherit from the AnotherFieldVisibilityCondition<TValue> base class, where the TValue generic specifies the data type of form components for which they are applicable.

A field’s depending visibility condition can only work with fields that precede it in the given form (i.e. are placed “above” the field in the form builder). The system cannot evaluate conditions based on the values of fields which are rendered later.

To define a depending visibility condition:

  1. Open your live site project in Visual Studio.

  2. Create a new class that inherits from the AnotherFieldVisibilityCondition<TValue>base class (available in the Kentico.Forms.Web.Mvc namespace). Substitute the TValuegeneric with the data typeof form components for which the condition is applicable (i.e., basic data types such as string,intdecimal).

  3. Annotate the class with the Serializable attribute.

  4. (Optional) In case of more complex visibility conditions, define custom properties and annotate them with the EditingComponent attribute to provide a configuration interface for users.

    
    
    
             // Defines a configuration interface for the condition
             // The 'EditingComponent' attribute specifies which form component is used as the property's value editor
             [EditingComponent(TextInputComponent.IDENTIFIER)]
             public string ConfigurableProperty { get; set; }
    
    
    
     
  5. Override the following method:

    • IsVisible– contains logic that determines a field’s visibility. The value of the field the condition depends on is stored in the DependeeFieldValue property. The method needs to return either true – the field is displayed, or false– the field remains hidden.
    
    
    
             // Contains custom visibility logic evaluated by the server
             // True indicates the field is displayed, false indicates the field is hidden
             public override bool IsVisible()
             {
                 return true;
             }
    
    
    
     
  6. Register the visibility condition in the system.

  7. Build the project

The visibility condition is now registered in the system and ready to be applied to form components of the corresponding type via the Form builder interface.

Example – Defining a depending visibility condition

The following example demonstrates the implementation of a condition that checks if the entered value belongs to the specified interval and displays or hides the depending field accordingly:




using System;

using Kentico.Forms.Web.Mvc;

using LearningKit.FormBuilder.VisibilityConditions;

// Registers the visibility condition in the system
[assembly: RegisterFormVisibilityCondition("IsBetweenVisibilityCondition", typeof(IsBetweenVisibilityCondition), "Value of another field lies between")]

namespace LearningKit.FormBuilder.VisibilityConditions
{
    [Serializable]
    public class IsBetweenVisibilityCondition : AnotherFieldVisibilityCondition<int?>
    {
        // Defines a configuration interface for the visibility condition
        // The 'EditingComponent' attribute specifies which form component is used as the property's value editor
        [EditingComponent(IntInputComponent.IDENTIFIER, Label = "Minimum", Order = 0)]
        public int Min { get; set; } = 0;

        [EditingComponent(IntInputComponent.IDENTIFIER, Label = "Maximum", Order = 1)]
        public int Max { get; set; } = 0;

        // Shows or hides the field based on the state of the dependee field
        public override bool IsVisible()
        {
            return (DependeeFieldValue >= Min) && (DependeeFieldValue <= Max);
        }
    }
}


The visibility condition is now available on the Form builder -> Visibilitytab of form fields.

Configuring the implemented visibility rule

Registering visibility conditions

To register a visibility condition, annotate the class with the RegisterFormVisbilityConditionassembly attribute. This attribute ensures the visibility condition is recognized by the system and available for use in the form builder interface. When registering the condition, specify the following parameters:

  • Identifier – a unique string identifier of the visibility condition.
  • VisibilityConditionType – the System.Type of the visibility condition class.
  • Name – sets the name of the visibility condition. Displayed when adding a visibility condition on the Form builder tab in the administration interface.

The Name parameter can be localized using resource string keys. See Localizing builder components.

The example below demonstrates the registration of a visibility condition:




[assembly: RegisterFormVisibilityCondition("CustomVisibilityCondition", typeof(CustomVisibilityCondition), "Custom visibility condition")]



Users can include the registered visibility condition when configuring the visibility of fields on the Form builder -> Visibility tab in the Forms application.