Preselect field value in dropdowns using a Form Field Widget

July 11, 2014 Digital Experience

Lately there were several instances where clients wanted to preselect form field values based on some criteria. This blog post will show how to achieve this functionality. For the sake of a sample I will look at a case where a dropdown list has a preselected item based on the URL, however you can imagine different scenarios of pre-populating data such as filling different location fields based on account information, context, geolocation and so on.

 

The first thing needed is creating a FormField. This process allows you to create and override some of the out of the box form widgets. I used the Thunder generated one as a template. From then I added my Dropdown in the template as well as some additional controls for the forms title text and description. This is standard procedure for overriding form widgets and you can review the source code below to see the implementation details. 

The dropdown is bound to a simple list with four values.

The key thing here is to perform the Url check inside the Initialize_Controls method. Initialize_Controls is one of the main extension points whenever you are building on top of UI elements in Sitefinity such as page widgets, form widgets etc. Overriding this method allows us to get references to all the UI elements inside a control - such as dropdowns for example - and modify the logic with which they are presented. 

Since the Field control class that the forms use is actually a separate control instance, it initializes itself and initializes all other controls it contains afterwards. Below is the manner in which I manipulate my dropdown:

protected override void InitializeControls(Telerik.Sitefinity.Web.UI.GenericContainer container)
        {
 
             
                    TitleLabel.Text = "State";
                    ddlStates.Items.Clear();
                    ddlStates.Items.Add(new ListItem("Select a State",""));
                    ddlStates.DataSource = itemList();
                   
                    //ddlStates.DataValueField = "Abbreviation";
                    //ddlStates.DataTextField = "Name";
                    ddlStates.DataBind();
                    ddlStates.TabIndex = this.TabIndex;
                    //this.ddlStates.SelectedIndexChanged += new EventHandler(ddlStates_SelectedIndexChanged);
                    //this.ddlStores.SelectedIndexChanged += new EventHandler(ddlStores_SelectedIndexChanged);
                    this.TabIndex = 0;
                    if (HttpContext.Current.Request.Url.AbsoluteUri.Contains("MyPage"))
                    {
                        ddlStates.SelectedValue = itemList().Last();
                    }
                   
        }

 

That’s all there is to it. You can download the sample and test it freely. Note that my sample checks for “MyPage” in the url so adjust accordingly.

Ivan D.Dimitrov