Make Country and State fields into dropdown list in Dynamics CRM 2011

By default, country and state/province fields in account, contact, lead,competitor and user entities in CRM 2011 are single line textboxes, So It is not user friendly to enter Country and State in these entities.

We do not want to create new fields for country and state with global optionsets, we wanted them to be dropdowns so that user can choose country and state easily.

Following JavaScript code will make the Country field into a dropdown that drives the State/Province field as well.  The State/Province field will be a dropdown for countries that have been configured (USA, Mexico and Canada countries and states are configured here, but it’s easy to add your own).  If a country has not been configured, the State/Province field falls back to the default textbox.

1.Create a new JavaScript Web Resource called CountriesAndStates.js and add following JavaScript code in that.

2.Add latest JQuery web resource(jquery-1.7.1.min.js) in form load, If you do not have latest JQuery file download from http://jquery.com/download/

3.Add a form load event that calls the LoadCountryAndStateFields method, passing in parameters for the name of the country and stateorprovince fields you wish to wire up (see images below).

CountriesAndStates.js

// Configures the country field to be a dropdown based on the Country object.
function LoadCountryField(countryFieldName, stateFieldName) {
    var $countryField = $('#' + countryFieldName);
    if ($countryField.length < 1) return;
    $countryField.hide();
    var selectedCountry = $countryField.val();
    var countryRequirementLevel = Xrm.Page.getAttribute(countryFieldName).getRequiredLevel();
    countryRequirementLevel = countryRequirementLevel == "required" ? 2 : countryRequirementLevel == "recommended" ? 1 : 0;
    var $countryDropdown = generateSelectBox('ddl_' + countryFieldName, countryRequirementLevel, Countries, selectedCountry);
    $('#' + countryFieldName + '_d').append($countryDropdown);
    $countryDropdown.change({ 'countryFieldName': countryFieldName, 'stateFieldName': stateFieldName }, handleCountryChanged);
    document.getElementById('ddl_' + countryFieldName).tabIndex = document.getElementById(countryFieldName).tabIndex;
    LoadStateField(stateFieldName, selectedCountry);
}
// Configures the stateOrProvince field to be a dropdown dependent on the value of the country dropdown. Values are pulled from the Countries object.
function LoadStateField(stateFieldName, selectedCountry) {
    var stateAttr = Xrm.Page.getAttribute(stateFieldName);
    var selectedState = stateAttr == null ? "" : stateAttr.getValue();
    var states = getStatesForCountry(selectedCountry);
    var $stateField = $('#' + stateFieldName);
    if (states == null || !$.isArray(states) || states.length < 1) {
        $('#ddl_' + stateFieldName).remove();
        $stateField.show();
        return;
    }
    $stateField.hide();
    var stateRequirementLevel = Xrm.Page.getAttribute(stateFieldName).getRequiredLevel();
    stateRequirementLevel = stateRequirementLevel == "required" ? 2 : stateRequirementLevel == "recommended" ? 1 : 0;
    var $stateDropdown = generateSelectBox('ddl_' + stateFieldName, stateRequirementLevel, states, selectedState);
    var $existingDropdown = $('#ddl_' + stateFieldName);
    if ($existingDropdown.length < 1)
        $('#' + stateFieldName + '_d').append($stateDropdown);
    else
        $existingDropdown.replaceWith($stateDropdown);
    $stateDropdown.change({ 'stateFieldName': stateFieldName }, handleStateChanged);
    $stateDropdown.change();
    document.getElementById('ddl_' + stateFieldName).tabIndex = document.getElementById(stateFieldName).tabIndex;
}
// Finds the states that go with selectedCountry, using the Countries object.
function getStatesForCountry(selectedCountry) {
    for (i in Countries) {
        var country = Countries[i];
        if (selectedCountry == country.name)
            return country.states;
    }
    return [];
}
// Sets the value of the country field to the newly selected value and reconfigures the dependent state dropdown.
function handleCountryChanged(eventData) {
    var stateFieldName = eventData.data.stateFieldName;
    var selectedCountry = setFieldFromDropdown(eventData.data.countryFieldName);
    LoadStateField(stateFieldName, selectedCountry);
}
// Sets the value of the stateOrProvince field to the newly selected value
function handleStateChanged(eventData) {
    setFieldFromDropdown(eventData.data.stateFieldName);
}
// Sets a field's value based on a related dropdown's value
function setFieldFromDropdown(fieldName) {
    var $dropdown = $('#ddl_' + fieldName);
    if ($dropdown.length != 1) return null;
    var selectedValue = $dropdown.find('option:selected:first').val();
    var attr = Xrm.Page.getAttribute(fieldName);
    if (attr != null) attr.setValue(selectedValue);
    return selectedValue;
}
// Generates a new select box with appropriate attributes for MS CRM 2011.
function generateSelectBox(id, requirementLevel, options, selectedValue) {
    var $ddl = $('<select id="' + id + '" class="ms-crm-SelectBox" req="' + requirementLevel + '" height="4" style="IME-MODE: auto; width: 100%"></select>');
    $ddl.append(jQuery('<option></option').val('').html(''));
    $.each(options, function (i, item) {
        $ddl.append(jQuery('<option></option').val(item.name).html(item.name));
        if (selectedValue == item.name)
            $ddl.find('option:last').attr('selected', 'selected');
    });
    return $ddl;
}
// Global array of countries and their respective states
var Countries = [
                    { "name": "United States", "abbr": "US", "states": [{ "name": "Alabama", "abbr": "AL" },
                                                                        { "name": "Alaska", "abbr": "AK" },
                                                                        { "name": "Arizona", "abbr": "AZ" },
                                                                        { "name": "Arkansas", "abbr": "AR" },
                                                                        { "name": "California", "abbr": "CA" },
                                                                        { "name": "Colorado", "abbr": "CO" },
                                                                        { "name": "Connecticut", "abbr": "CT" },
                                                                        { "name": "Delaware", "abbr": "DE" },
                                                                        { "name": "District Of Columbia", "abbr": "DC" },
                                                                        { "name": "Florida", "abbr": "FL" },
                                                                        { "name": "Georgia", "abbr": "GA" },
                                                                        { "name": "Hawaii", "abbr": "HI" },
                                                                        { "name": "Idaho", "abbr": "ID" },
                                                                        { "name": "Illinois", "abbr": "IL" },
                                                                        { "name": "Indiana", "abbr": "IN" },
                                                                        { "name": "Iowa", "abbr": "IA" },
                                                                        { "name": "Kansas", "abbr": "KS" },
                                                                        { "name": "Kentucky", "abbr": "KY" },
                                                                        { "name": "Louisiana", "abbr": "LA" },
                                                                        { "name": "Maine", "abbr": "ME" },
                                                                        { "name": "Maryland", "abbr": "MD" },
                                                                        { "name": "Massachusetts", "abbr": "MA" },
                                                                        { "name": "Michigan", "abbr": "MI" },
                                                                        { "name": "Minnesota", "abbr": "MN" },
                                                                        { "name": "Mississippi", "abbr": "MS" },
                                                                        { "name": "Missouri", "abbr": "MO" },
                                                                        { "name": "Montana", "abbr": "MT" },
                                                                        { "name": "Nebraska", "abbr": "NE" },
                                                                        { "name": "Nevada", "abbr": "NV" },
                                                                        { "name": "New Hampshire", "abbr": "NH" },
                                                                        { "name": "New Jersey", "abbr": "NJ" },
                                                                        { "name": "New Mexico", "abbr": "NM" },
                                                                        { "name": "New York", "abbr": "NY" },
                                                                        { "name": "North Carolina", "abbr": "NC" },
                                                                        { "name": "North Dakota", "abbr": "ND" },
                                                                        { "name": "Ohio", "abbr": "OH" },
                                                                        { "name": "Oklahoma", "abbr": "OK" },
                                                                        { "name": "Oregon", "abbr": "OR" },
                                                                        { "name": "Pennsylvania", "abbr": "PA" },
                                                                        { "name": "Puerto Rico", "abbr": "PR" },
                                                                        { "name": "Rhode Island", "abbr": "RI" },
                                                                        { "name": "South Carolina", "abbr": "SC" },
                                                                        { "name": "South Dakota", "abbr": "SD" },
                                                                        { "name": "Tennessee", "abbr": "TN" },
                                                                        { "name": "Texas", "abbr": "TX" },
                                                                        { "name": "Utah", "abbr": "UT" },
                                                                        { "name": "Vermont", "abbr": "VT" },
                                                                        { "name": "Virgin Islands", "abbr": "VI" },
                                                                        { "name": "Virginia", "abbr": "VA" },
                                                                        { "name": "Washington", "abbr": "WA" },
                                                                        { "name": "West Virginia", "abbr": "WV" },
                                                                        { "name": "Wisconsin", "abbr": "WI" },
                                                                        { "name": "Wyoming", "abbr": "WY"}]
                    },
{ "name": "Canada", "abbr": "CA", "states": [{ "name": "Alberta", "abbr": "AB" },
                                                                    { "name": "British Columbia", "abbr": "BC" },
                                                                    { "name": "Manitoba", "abbr": "MB" },
                                                                    { "name": "New Brunswick", "abbr": "NB" },
                                                                    { "name": "Newfoundland and Labrador", "abbr": "NL" },
                                                                    { "name": "Northwest Territories", "abbr": "NT" },
                                                                    { "name": "Nova Scotia", "abbr": "NS" },
                                                                    { "name": "Nunavut", "abbr": "NU" },
                                                                    { "name": "Ontario", "abbr": "ON" },
                                                                    { "name": "Prince Edward Island", "abbr": "PE" },
                                                                    { "name": "Quebec", "abbr": "QC" },
                                                                    { "name": "Saskatchewan", "abbr": "SK" },
                                                                    { "name": "Yukon", "abbr": "YT"}]
},
{ "name": "Mexico", "abbr": "MX", "states": [
					      { "name": "Aguascalientes", "abbr": "AGS" },
		                  { "name": "Baja California Norte", "abbr": "BCN" },
						  { "name": "Baja California Sur", "abbr": "BCS" },
						  { "name": "Campeche", "abbr": "CAM" },
						  { "name": "Chiapas", "abbr": "CHIS" },
						  { "name": "Chihuahua", "abbr": "CHIH" },
						  { "name": "Coahuila", "abbr": "COAH" },
						  { "name": "Colima", "abbr": "COL" },
						  { "name": "Distrito Federal", "abbr": "DF" },
						  { "name": "Durango", "abbr": "DGO" },
						  { "name": "Guanajuato", "abbr": "GTO" },
						  { "name": "Guerrero", "abbr": "GRO" },
						  { "name": "Hidalgo", "abbr": "HGO" },
						  { "name": "Jalisco", "abbr": "JAL" },
						  { "name": "México - Estado de", "abbr": "EDM" },
						  { "name": "Michoacán", "abbr": "MICH" },
						  { "name": "Morelos", "abbr": "MOR" },
						  { "name": "Nayarit", "abbr": "NAY" },
						  { "name": "Nuevo León", "abbr": "NL" },
						  { "name": "Oaxaca", "abbr": "OAX" },
						  { "name": "Puebla", "abbr": "PUE" },
						  { "name": "Querétaro", "abbr": "QRO" },
						  { "name": "Quintana Roo", "abbr": "QROO" },
						  { "name": "San Luis Potosí", "abbr": "SLP" },
						  { "name": "Sinaloa", "abbr": "SIN" },
						  { "name": "Sonora", "abbr": "SON" },
						  { "name": "Tabasco", "abbr": "TAB" },
						  { "name": "Tamaulipas", "abbr": "TAMPS" },
						  { "name": "Tlaxcala", "abbr": "TLAX" },
						  { "name": "Veracruz", "abbr": "VER" },
						  { "name": "Yucatán", "abbr": "YUC" },
                          { "name": "Zacatecas", "abbr": "ZAC"}]
},
{ "name": "Other International", "abbr": "OINT", "states": [] }
];

Here’s what the configuration screen might look like:

2_Form Properties

1_Form Handler Properties

Here’s what the result looks like with states configured for the selected country:

Populated Country and State values in dropdown lists

3_Account Demographics

Country Dropdown list

4_Country Dropdownlist

State dropdown list
5_State Dropdownlist

Advertisements

19 thoughts on “Make Country and State fields into dropdown list in Dynamics CRM 2011

  1. This is awesome! Thank you!! Now I like to pre-select “United States” by default… I’ve been trying but kept failing.

    • I made the following changes to switch to storing abbr values:

      line 43: if (selectedCountry == country.abbr)
      line 72: $ddl.append(jQuery(‘</option').val(item.abbr).html(item.name));
      line 73: if (selectedValue == item.abbr)

  2. Does anyone know how to set a default country on page load? The majority of our clients are UK based so I have updated the countries array to include the United Kingdom and would like the form to load this by default, and therefore load the ‘address1_stateorprovince’ drop down too.

    • While you can put such a change into this script, you could also make this change separate entirely. Such as an OnLoad script that just calls:

      //If country is blank
      if (Xrm.Page.getAttribute(“address1_country”).GetValue() == null)
      {
      //Set country to united kingdom
      Xrm.Page.getAttribute(“address1_country”).SetValue(“United Kingdom”);
      }

      I might go a step further and check that the form is in create mode before running this feature if you don’t want to automatically change the country of existing records with no country.

      • Woo hoo! Thanks Kevin, yes I got this to work. Actually built it into the original code. I amended:

        line 6: var selectedCountry = $countryField.val();

        to

        var selectedCountry;
        if (Xrm.Page.ui.getFormType() == 1) {
        selectedCountry = “United Kingdom”;
        } else {
        selectedCountry = $countryField.val();
        }

        If anyone else needed to have a default country load up just change the “United Kingdom” to whatever country you have in your Countries array.

  3. I am also having issue with crm 2015. selected value does not show on re-opening the form. For split second it show and then disappear. I checked in database where the information is being saved properly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s