-- HR-130 handled organization autocomplete
[civicrm-core.git] / js / jquery / jquery.crmContactField.js
1 (function($, CRM) {
2
3 /**
4 * Setup a contact widget for use in CRUD forms. The form element stores a contact ID
5 * but displays a name/label.
6 *
7 * Usage:
8 * <INPUT type="text" name="my_contact_id" value="123" />
9 * <SCRIPT type="text/javascript">
10 * $('[name=my_contact_id]').crmContactField();
11 * $('[name=my_contact_id]').on('change', function(){
12 * console.log("the new contact id is ", $(this).val());
13 * });
14 * </SCRIPT>
15 *
16 * Note: The given form element is the canonical representation of the selected contact-ID.
17 * To display/enter the contact by name, the contact-ID field will be hidden, and a helper
18 * widget will be inserted. The values will be synced between the two.
19 *
20 * Cases to consider/test:
21 * - When initializing, the read the contact-ID and set the contact-label
22 * - When unsetting(blanking) the contact-label, also unset (blank) the contact-ID
23 * - If third party code updates the hidden value, then one must trigger a 'change'
24 * event to update the visible widget.
25 */
26 $.fn.crmContactField = function() {
27 return this.each(function(){
28 var urlParams = 'className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1';
29 var hiddenEl = this;
30 var widgetEl = $('<input type="text" />');
31
32 var activeContactId = null;
33 // For organization autocomplete
34 if($(this).attr('autocompleteType') == 'org') {
35 var urlParams = urlParams + '&org=1';
36 }
37 var contactUrl = CRM.url('civicrm/ajax/rest', urlParams);
38 var setContactId = function(newContactId) {
39 if (newContactId != $(hiddenEl).val()) {
40 $(hiddenEl).val(newContactId);
41 $(hiddenEl).trigger('change');
42 }
43 if (activeContactId != newContactId) {
44 activeContactId = newContactId;
45
46 if (activeContactId) {
47 // lookup the name
48 $(widgetEl).css({visibility: 'hidden'}); // don't allow input during ajax
49 $.ajax({
50 url : contactUrl + '&id=' + newContactId,
51 async : false,
52 success : function(html){
53 var htmlText = html.split( '|' , 2);
54 $(widgetEl).val(htmlText[0]);
55 $(widgetEl).css({visibility: 'visible'});
56 }
57 });
58 } else {
59 // there is no name to lookup - just show a blank
60 $(widgetEl).val('');
61 }
62 }
63 };
64
65 $(hiddenEl).after(widgetEl);
66 $(hiddenEl).hide();
67 $(widgetEl).autocomplete(contactUrl, {
68 width: 200,
69 selectFirst: false,
70 minChars: 1,
71 matchContains: true,
72 delay: 400
73 }).result(function(event, data) {
74 activeContactId = data[1];
75 setContactId(activeContactId);
76 }).bind('change blur', function() {
77 if (! $(widgetEl).val()) {
78 activeContactId = '';
79 setContactId(activeContactId);
80 }
81 });
82
83 $(hiddenEl).bind('change', function(){
84 setContactId($(this).val());
85 });
86 setContactId($(hiddenEl).val());
87 });
88 };
89
90 })(jQuery, CRM);