Saturday, June 29, 2013

Sitecore How-To: Sitecore Country and Region Dropdowns

We had a couple people in the Guild ask about country and region DropDownLists so thought Dennis Augustine and I thought we would write an article on it. Problem: In our application we require a country and region picker. When someone chooses a company we need to filter the region picker.Solution: This can be accomplished by adding two DropDownList controls to your SubLayout. Call one ddlCountry and the other ddlRegion. In the content tree under a shared lookup area create a folder called "Country" under this folder add the countries with key as country code and phrase as country name. Next under each country create a folder called "Regions" store all the regions in this folder. I use DictionaryEntry as my Sitecore Data Template for the country and regions.On Page_load you would call GetCountries() and assign it to the ddlCountries.DataSource Property.

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{ ddlRegion.DataSource = GetRegions(ddlCountry.SelectedValue); ddlRegion.DataValueField = "Key"; ddlRegion.DataTextField = "Phrase"; ddlRegion.DataBind();
}Next add the following code to the sublayout. Ideally later you would store these in a library for use late in other parts of your code. Also note that you would need to change "SiteSettings.LookupPath" to the path where you are storing your countries in the tree. This setting occurs a couple times in my code below.///<summary> /// Getting children items by parent item path ///</summary> /// <param name="itemPath"></param> /// <returns>List<LookupItem></returns> public static List<LookupItem> GetLookupItemChildren(string itemPath) { Item item = Sitecore.Context.Database.Items[itemPath]; List<LookupItem> lst = new List<LookupItem>();