CRM 2011 Zip Code Lookup


/ Published in: JavaScript
Save to your folder(s)

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/ )


Copy this code and paste it in your HTML
  1. ///<reference path="XrmPage-vsdoc.js"/>
  2. ///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>
  3.  
  4. /*
  5. - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
  6. - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
  7. - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
  8. - This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional,
  9. to allow the choice of using full or abbreviated state name, as well as to provide support for multiple
  10. browsers using the JQuery library.
  11. - NOTE: Code requires that the page using it first includes a reference to JQuery and JSON. Here is a link to a
  12. managed CRM solution containing JQuery and JSON2 Web Resources that you can include on your CRM forms:
  13. https://skydrive.live.com/embedicon.aspx/.Public/jQueryCRM2011_1_6_0_0_managed.zip?cid=0f98a78f1c3c4457&sc=documents
  14.  
  15. o Parameters:
  16. -- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
  17. -- The user is not required to enter the country (will default to US)
  18. -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
  19. */
  20. var _cityTypeName = "Town";
  21. var _stateTypeName = "State";
  22. var _cityDdl;
  23. var _savedCity;
  24. var _savedState;
  25. var _cityFieldName;
  26. var _stateFieldName;
  27. var _heldState;
  28. var _heldStateCode;
  29. var _isDropdown;
  30. var _matchFound;
  31.  
  32. function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {
  33.  
  34. _cityFieldName = cityFieldName;
  35. _stateFieldName = stateFieldName;
  36. _savedCity = Xrm.Page.getAttribute(_cityFieldName).getValue();
  37. _savedState = Xrm.Page.getAttribute(_stateFieldName).getValue();
  38. Xrm.Page.getAttribute(_cityFieldName).setValue("Localizing...");
  39. Xrm.Page.getAttribute(_stateFieldName).setValue(null);
  40. _isDropdown = false;
  41.  
  42. if (arguments.length < 4) {
  43. abbreviateState = false;
  44. }
  45.  
  46. // Verify that the field is valid
  47. var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
  48. if (zip != null) {
  49.  
  50. // define Yahoo YQL query
  51. var wsql = 'select * from geo.places where text="' + zip + '"';
  52.  
  53. // pass country
  54. var country = null;
  55. if (arguments.length > 4 && countryFieldName.length > 0) {
  56. country = Xrm.Page.getAttribute(countryFieldName).getValue();
  57. }
  58. if (country == null) {
  59. country = "United States";
  60. }
  61. wsql = wsql + ' and country="' + country + '"';
  62.  
  63. // get url to Yahoo YQL service
  64. var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';
  65.  
  66. _matchFound = false;
  67. setTimeout(ResetLocation, 5000);
  68. $.getJSON(yqlUrl, function (r) {
  69.  
  70. var city;
  71. if (r.query.count == 1) {
  72.  
  73. var node;
  74. for (key in r.query.results.place) {
  75.  
  76. node = r.query.results.place[key];
  77. if (node && node.type && node.type == _cityTypeName) {
  78. city = node.content;
  79. }
  80. else if (node && node.type && node.type == _stateTypeName) {
  81. _heldState = node.content;
  82. if (abbreviateState) {
  83. _heldState = node.code.slice(-2);
  84. }
  85. }
  86.  
  87. }
  88.  
  89. if (city != null && city.length > 0) {
  90. Xrm.Page.getAttribute(_cityFieldName).setValue(city);
  91. _matchFound = true;
  92. _savedCity = city;
  93. SetState();
  94. }
  95. else {
  96. BuildCityDropdown(r.query.results.place.woeid, _cityFieldName);
  97. }
  98.  
  99. }
  100. else {
  101. alert("ZipCode cannot be found");
  102. // If zip code is not found, restore the original values
  103. Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
  104. Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
  105. }
  106. });
  107. }
  108. else {
  109. // If zip code is not entered, restore the original values
  110. Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
  111. Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
  112. }
  113. }
  114.  
  115. function ResetLocation() {
  116. if (!_matchFound) {
  117. Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
  118. Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
  119. }
  120. }
  121.  
  122. function SetState() {
  123. var stateAttribute = Xrm.Page.getAttribute(_stateFieldName);
  124. if (stateAttribute.getAttributeType() == "optionset") {
  125. var options = stateAttribute.getOptions();
  126. for (var i = 0; i < options.length; i++) {
  127. if (options[i].text == _heldState) {
  128. stateAttribute.setValue(options[i].value);
  129. _savedState = options[i].value;
  130. }
  131. }
  132. }
  133. else {
  134. stateAttribute.setValue(_heldState);
  135. _savedState = _heldState;
  136. }
  137. }
  138.  
  139. function BuildCityDropdown(woeid, _cityFieldName) {
  140.  
  141. if (woeid != null && woeid.length > 0) {
  142.  
  143. // define Yahoo YQL query for child places
  144. var wsql = "select * from geo.places.children where parent_woeid=" + woeid;
  145.  
  146. // get url to Yahoo YQL service
  147. var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';
  148.  
  149. $.getJSON(yqlUrl, function (r) {
  150.  
  151. if (r.query.count > 0) {
  152. _cityDdl = $("#" + _cityFieldName);
  153. _cityDdl.MakeDynamicDropDown();
  154. _cityDdl.DynamicDropDown.SetDefaultCss(
  155. {
  156. "background-color" : "Black",
  157. "border-radius" : "100px",
  158. "width" : $("#" + _cityFieldName).css("width"),
  159. "padding" : "10px"
  160. });
  161. _cityDdl.DynamicDropDown.SetDefaultItemCss(
  162. {
  163. "background-color" : "White",
  164. "border" : "2px solid #CCC"
  165. });
  166. _cityDdl.DynamicDropDown.SetDefaultItemHoverCss(
  167. {
  168. "background-color" : "#CCC",
  169. "border" : "2px solid #333"
  170. });
  171. _cityDdl.DynamicDropDown.CreateHeader("Select a City...",
  172. {
  173. "font-weight" : "bold",
  174. "font-style" : "italic"
  175. });
  176.  
  177. _cityDdl.DynamicDropDown.Clear();
  178. var place;
  179. for (var i = 0; i < r.query.count; i++) {
  180. place = r.query.results.place[i];
  181.  
  182. var node;
  183. var innerDiv;
  184. for (key in place) {
  185. node = place[key];
  186. if (node && node.type && node.type == _cityTypeName) {
  187. _cityDdl.DynamicDropDown.AddItem(node.content, node.content);
  188. }
  189. }
  190. }
  191.  
  192. _cityDdl.DynamicDropDown.bind("itemselected", function () {
  193. Xrm.Page.getAttribute(_cityFieldName).setValue(_cityDdl.DynamicDropDown.SelectedText());
  194. _matchFound = true;
  195. SetState();
  196. _cityDdl.DynamicDropDown.Close(300);
  197. });
  198.  
  199. _cityDdl.DynamicDropDown.Open(300);
  200. }
  201. else {
  202. alert("Valid city cannot be found");
  203. Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
  204. Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
  205. }
  206. });
  207.  
  208. }
  209. }
  210.  
  211. $(document).bind('click', function (event) {
  212. if (_cityDdl && _cityDdl.DynamicDropDown.IsOpen() && _cityDdl.DynamicDropDown.TargetIsThis(event.target.id)) {
  213. Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
  214. Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
  215. _cityDdl.DynamicDropDown.Close(300);
  216. }
  217. });
  218.  
  219. ;(function ($) {
  220. var DynamicDropDown = function () {
  221. var _ddKey = "dyndd_";
  222. var _background;
  223. var _obj;
  224. var _spanDiv;
  225. var _defaultMap;
  226. var _defaultHoverMap;
  227. var _items;
  228. var _selectedIndex;
  229. var _selectedValue;
  230. var _selectedText;
  231. var _isDropdownOpen;
  232.  
  233. /*********************** Events ***********************/
  234.  
  235. var onitemselected = null;
  236.  
  237. /*********************** Constructor ***********************/
  238.  
  239. this.Create = function () {
  240. _obj = $('<div id="' + _ddKey + 'Body"></div>');
  241. _obj.css({
  242. 'display' : 'none',
  243. 'position' : 'absolute',
  244. 'top' : '0px',
  245. 'left' : '0px',
  246. 'z-index' : '1001'
  247. });
  248.  
  249. _background = $('<div id="' + _ddKey + 'bg"></div>');
  250. _background.css({
  251. 'display' : 'none',
  252. 'background-color' : '#000',
  253. 'opacity': '0.8',
  254. 'filter' : 'alpha(opacity=80)',
  255. 'position' : 'absolute',
  256. 'top' : '0px',
  257. 'left' : '0px',
  258. 'min-width' : '100%',
  259. 'min-height' : '100%',
  260. 'width' : '100%',
  261. 'height' : '100%',
  262. 'z-index' : '1000'
  263. });
  264.  
  265. $(document.body).append(_obj);
  266. $(document.body).append(_background);
  267.  
  268. _obj.bind('click', function (event) {
  269. if (event.target.id.indexOf(_ddKey + "Item") > -1) {
  270. _selectedIndex = parseInt(event.target.id.replace(_ddKey + "Item", ""));
  271. if (!isNaN(_selectedIndex)) {
  272. _selectedValue = _items[_selectedIndex].value;
  273. _selectedText = _items[_selectedIndex].text;
  274. onitemselected();
  275. }
  276. }
  277. });
  278.  
  279. _items = [];
  280. return _obj;
  281. };
  282.  
  283. /*********************** Public Methods ***********************/
  284.  
  285. this.SetDefaultCss = function (cssMap) {
  286. _obj.css(cssMap);
  287. };
  288.  
  289. this.SetDefaultItemCss = function (cssMap) {
  290. _defaultMap = cssMap;
  291. };
  292.  
  293. this.SetDefaultItemHoverCss = function (cssMap) {
  294. _defaultHoverMap = cssMap;
  295. };
  296.  
  297. this.CreateHeader = function (text, cssMap) {
  298. _spanDiv = $('<div id="' + _ddKey + 'Header"><span>' + text + '</span></div>');
  299. appendDiv(_spanDiv, cssMap);
  300. };
  301.  
  302. this.AddItem = function (value, text, cssMap) {
  303. var itemCount = _items.length;
  304. _items[itemCount] = { value : value, text : text };
  305.  
  306. var innerDiv = $('<div id="' + _ddKey + 'Item' + itemCount + '">' + text + '</div>');
  307. innerDiv.mouseover(function () {
  308. $(this).css(_defaultHoverMap);
  309. });
  310. appendDiv(innerDiv, cssMap);
  311. };
  312.  
  313. this.Open = function (speed) {
  314. var parent = window;
  315. _obj.css({
  316. "top": ((($(parent).height() - _obj.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
  317. "left": ((($(parent).width() - _obj.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
  318. });
  319.  
  320. _background.fadeIn(speed);
  321. _obj.fadeIn(speed);
  322. _isDropdownOpen = true;
  323. };
  324.  
  325. this.Close = function (speed) {
  326. _obj.fadeOut(speed);
  327. _background.fadeOut(speed);
  328. _isDropdownOpen = false;
  329. };
  330.  
  331. this.IsOpen = function () {
  332. return _isDropdownOpen;
  333. };
  334.  
  335. this.SelectedIndex = function () {
  336. return _selectedIndex;
  337. };
  338.  
  339. this.SelectedValue = function () {
  340. return _selectedValue;
  341. };
  342.  
  343. this.SelectedText = function () {
  344. return _selectedText;
  345. };
  346.  
  347. this.Clear = function () {
  348. _obj.children().each(function (key, value) {
  349. if (value.id.indexOf(_ddKey + "Item") > -1) {
  350. $(value).remove();
  351. }
  352. });
  353. };
  354.  
  355. this.ClearSelected = function () {
  356. _selectedIndex = -1;
  357. _selectedValue = "";
  358. _selectedText = "";
  359. };
  360.  
  361. this.TargetIsThis = function (targetId) {
  362. return (targetId.indexOf(_ddKey) > -1);
  363. };
  364.  
  365. this.bind = function (event, handler) {
  366. if (event.toLowerCase() == "itemselected") {
  367. onitemselected = handler;
  368. }
  369. };
  370.  
  371. /*********************** Private Methods ***********************/
  372.  
  373. var appendDiv = function (div, cssMap) {
  374. var newMap = [];
  375. for (key in _defaultMap) {
  376. newMap[key] = _defaultMap[key];
  377. }
  378. for (key in cssMap) {
  379. newMap[key] = cssMap[key];
  380. }
  381. div.css(newMap);
  382. div.mouseout(function () {
  383. $(this).css(newMap);
  384. });
  385. _obj.append(div);
  386. };
  387.  
  388. };
  389.  
  390. $.fn.MakeDynamicDropDown = function () {
  391. // Return early if this element already has a plugin instance
  392. if (this.DynamicDropDown) return;
  393.  
  394. // Store plugin object as a property on the element
  395. this.DynamicDropDown = new DynamicDropDown();
  396. this.DynamicDropDown.Create();
  397. };
  398.  
  399. })(jQuery);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.