/ Published in: JavaScript
Allows the ability to fill City and State fields in CRM 2011 based on the value of a Zip Code field (and optionally Country).
Requires JQuery and JSON
Uses Yahoo geocode service
Originally written by Bill Caldwell ( http://dynamicscrmdenver.com/2012/05/25/dynamics-crm-2011-javascript-zipcodepostal-code-lookup/ )
Requires JQuery and JSON
Uses Yahoo geocode service
Originally written by Bill Caldwell ( http://dynamicscrmdenver.com/2012/05/25/dynamics-crm-2011-javascript-zipcodepostal-code-lookup/ )
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
///<reference path="XrmPage-vsdoc.js"/> ///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/> /* - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality - This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, to allow the choice of using full or abbreviated state name, as well as to provide support for multiple browsers using the JQuery library. - NOTE: Code requires that the page using it first includes a reference to JQuery and JSON. Here is a link to a managed CRM solution containing JQuery and JSON2 Web Resources that you can include on your CRM forms: https://skydrive.live.com/embedicon.aspx/.Public/jQueryCRM2011_1_6_0_0_managed.zip?cid=0f98a78f1c3c4457&sc=documents o Parameters: -- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name -- The user is not required to enter the country (will default to US) -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country"); */ var _cityTypeName = "Town"; var _stateTypeName = "State"; var _cityDdl; var _savedCity; var _savedState; var _cityFieldName; var _stateFieldName; var _heldState; var _heldStateCode; var _isDropdown; var _matchFound; function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) { _cityFieldName = cityFieldName; _stateFieldName = stateFieldName; _savedCity = Xrm.Page.getAttribute(_cityFieldName).getValue(); _savedState = Xrm.Page.getAttribute(_stateFieldName).getValue(); Xrm.Page.getAttribute(_cityFieldName).setValue("Localizing..."); Xrm.Page.getAttribute(_stateFieldName).setValue(null); _isDropdown = false; if (arguments.length < 4) { abbreviateState = false; } // Verify that the field is valid var zip = Xrm.Page.getAttribute(zipFieldName).getValue(); if (zip != null) { // define Yahoo YQL query var wsql = 'select * from geo.places where text="' + zip + '"'; // pass country var country = null; if (arguments.length > 4 && countryFieldName.length > 0) { country = Xrm.Page.getAttribute(countryFieldName).getValue(); } if (country == null) { country = "United States"; } wsql = wsql + ' and country="' + country + '"'; // get url to Yahoo YQL service var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?'; _matchFound = false; setTimeout(ResetLocation, 5000); $.getJSON(yqlUrl, function (r) { var city; if (r.query.count == 1) { var node; for (key in r.query.results.place) { node = r.query.results.place[key]; if (node && node.type && node.type == _cityTypeName) { city = node.content; } else if (node && node.type && node.type == _stateTypeName) { _heldState = node.content; if (abbreviateState) { _heldState = node.code.slice(-2); } } } if (city != null && city.length > 0) { Xrm.Page.getAttribute(_cityFieldName).setValue(city); _matchFound = true; _savedCity = city; SetState(); } else { BuildCityDropdown(r.query.results.place.woeid, _cityFieldName); } } else { alert("ZipCode cannot be found"); // If zip code is not found, restore the original values Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity); Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState); } }); } else { // If zip code is not entered, restore the original values Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity); Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState); } } function ResetLocation() { if (!_matchFound) { Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity); Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState); } } function SetState() { var stateAttribute = Xrm.Page.getAttribute(_stateFieldName); if (stateAttribute.getAttributeType() == "optionset") { var options = stateAttribute.getOptions(); for (var i = 0; i < options.length; i++) { if (options[i].text == _heldState) { stateAttribute.setValue(options[i].value); _savedState = options[i].value; } } } else { stateAttribute.setValue(_heldState); _savedState = _heldState; } } function BuildCityDropdown(woeid, _cityFieldName) { if (woeid != null && woeid.length > 0) { // define Yahoo YQL query for child places var wsql = "select * from geo.places.children where parent_woeid=" + woeid; // get url to Yahoo YQL service var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?'; $.getJSON(yqlUrl, function (r) { if (r.query.count > 0) { _cityDdl = $("#" + _cityFieldName); _cityDdl.MakeDynamicDropDown(); _cityDdl.DynamicDropDown.SetDefaultCss( { "background-color" : "Black", "border-radius" : "100px", "width" : $("#" + _cityFieldName).css("width"), "padding" : "10px" }); _cityDdl.DynamicDropDown.SetDefaultItemCss( { "background-color" : "White", "border" : "2px solid #CCC" }); _cityDdl.DynamicDropDown.SetDefaultItemHoverCss( { "background-color" : "#CCC", "border" : "2px solid #333" }); _cityDdl.DynamicDropDown.CreateHeader("Select a City...", { "font-weight" : "bold", "font-style" : "italic" }); _cityDdl.DynamicDropDown.Clear(); var place; for (var i = 0; i < r.query.count; i++) { place = r.query.results.place[i]; var node; var innerDiv; for (key in place) { node = place[key]; if (node && node.type && node.type == _cityTypeName) { _cityDdl.DynamicDropDown.AddItem(node.content, node.content); } } } _cityDdl.DynamicDropDown.bind("itemselected", function () { Xrm.Page.getAttribute(_cityFieldName).setValue(_cityDdl.DynamicDropDown.SelectedText()); _matchFound = true; SetState(); _cityDdl.DynamicDropDown.Close(300); }); _cityDdl.DynamicDropDown.Open(300); } else { alert("Valid city cannot be found"); Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity); Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState); } }); } } $(document).bind('click', function (event) { if (_cityDdl && _cityDdl.DynamicDropDown.IsOpen() && _cityDdl.DynamicDropDown.TargetIsThis(event.target.id)) { Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity); Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState); _cityDdl.DynamicDropDown.Close(300); } }); ;(function ($) { var DynamicDropDown = function () { var _ddKey = "dyndd_"; var _background; var _obj; var _spanDiv; var _defaultMap; var _defaultHoverMap; var _items; var _selectedIndex; var _selectedValue; var _selectedText; var _isDropdownOpen; /*********************** Events ***********************/ var onitemselected = null; /*********************** Constructor ***********************/ this.Create = function () { _obj = $('<div id="' + _ddKey + 'Body"></div>'); _obj.css({ 'display' : 'none', 'position' : 'absolute', 'top' : '0px', 'left' : '0px', 'z-index' : '1001' }); _background = $('<div id="' + _ddKey + 'bg"></div>'); _background.css({ 'display' : 'none', 'background-color' : '#000', 'opacity': '0.8', 'filter' : 'alpha(opacity=80)', 'position' : 'absolute', 'top' : '0px', 'left' : '0px', 'min-width' : '100%', 'min-height' : '100%', 'width' : '100%', 'height' : '100%', 'z-index' : '1000' }); $(document.body).append(_obj); $(document.body).append(_background); _obj.bind('click', function (event) { if (event.target.id.indexOf(_ddKey + "Item") > -1) { _selectedIndex = parseInt(event.target.id.replace(_ddKey + "Item", "")); if (!isNaN(_selectedIndex)) { _selectedValue = _items[_selectedIndex].value; _selectedText = _items[_selectedIndex].text; onitemselected(); } } }); _items = []; return _obj; }; /*********************** Public Methods ***********************/ this.SetDefaultCss = function (cssMap) { _obj.css(cssMap); }; this.SetDefaultItemCss = function (cssMap) { _defaultMap = cssMap; }; this.SetDefaultItemHoverCss = function (cssMap) { _defaultHoverMap = cssMap; }; this.CreateHeader = function (text, cssMap) { _spanDiv = $('<div id="' + _ddKey + 'Header"><span>' + text + '</span></div>'); appendDiv(_spanDiv, cssMap); }; this.AddItem = function (value, text, cssMap) { var itemCount = _items.length; _items[itemCount] = { value : value, text : text }; var innerDiv = $('<div id="' + _ddKey + 'Item' + itemCount + '">' + text + '</div>'); innerDiv.mouseover(function () { $(this).css(_defaultHoverMap); }); appendDiv(innerDiv, cssMap); }; this.Open = function (speed) { var parent = window; _obj.css({ "top": ((($(parent).height() - _obj.outerHeight()) / 2) + $(parent).scrollTop() + "px"), "left": ((($(parent).width() - _obj.outerWidth()) / 2) + $(parent).scrollLeft() + "px") }); _background.fadeIn(speed); _obj.fadeIn(speed); _isDropdownOpen = true; }; this.Close = function (speed) { _obj.fadeOut(speed); _background.fadeOut(speed); _isDropdownOpen = false; }; this.IsOpen = function () { return _isDropdownOpen; }; this.SelectedIndex = function () { return _selectedIndex; }; this.SelectedValue = function () { return _selectedValue; }; this.SelectedText = function () { return _selectedText; }; this.Clear = function () { _obj.children().each(function (key, value) { if (value.id.indexOf(_ddKey + "Item") > -1) { $(value).remove(); } }); }; this.ClearSelected = function () { _selectedIndex = -1; _selectedValue = ""; _selectedText = ""; }; this.TargetIsThis = function (targetId) { return (targetId.indexOf(_ddKey) > -1); }; this.bind = function (event, handler) { if (event.toLowerCase() == "itemselected") { onitemselected = handler; } }; /*********************** Private Methods ***********************/ var appendDiv = function (div, cssMap) { var newMap = []; for (key in _defaultMap) { newMap[key] = _defaultMap[key]; } for (key in cssMap) { newMap[key] = cssMap[key]; } div.css(newMap); div.mouseout(function () { $(this).css(newMap); }); _obj.append(div); }; }; $.fn.MakeDynamicDropDown = function () { // Return early if this element already has a plugin instance if (this.DynamicDropDown) return; // Store plugin object as a property on the element this.DynamicDropDown = new DynamicDropDown(); this.DynamicDropDown.Create(); }; })(jQuery);