Merge pull request #1625 from pradpnayak/CRM-13340
[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 contactUrl = CRM.url('civicrm/ajax/rest', '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 var setContactId = function(newContactId) {
34 if (newContactId != $(hiddenEl).val()) {
35 $(hiddenEl).val(newContactId);
36 $(hiddenEl).trigger('change');
37 }
38 if (activeContactId != newContactId) {
39 activeContactId = newContactId;
40
41 if (activeContactId) {
42 // lookup the name
43 $(widgetEl).css({visibility: 'hidden'}); // don't allow input during ajax
44 $.ajax({
45 url : contactUrl + '&id=' + newContactId,
46 async : false,
47 success : function(html){
48 var htmlText = html.split( '|' , 2);
49 $(widgetEl).val(htmlText[0]);
50 $(widgetEl).css({visibility: 'visible'});
51 }
52 });
53 } else {
54 // there is no name to lookup - just show a blank
55 $(widgetEl).val('');
56 }
57 }
58 };
59
60 $(hiddenEl).after(widgetEl);
61 $(hiddenEl).hide();
62 $(widgetEl).autocomplete(contactUrl, {
63 width: 200,
64 selectFirst: false,
65 minChars: 1,
66 matchContains: true,
67 delay: 400
68 }).result(function(event, data) {
69 activeContactId = data[1];
70 setContactId(activeContactId);
71 }).bind('change blur', function() {
72 if (! $(widgetEl).val()) {
73 activeContactId = '';
74 setContactId(activeContactId);
75 }
76 });
77
78 $(hiddenEl).bind('change', function(){
79 setContactId($(this).val());
80 });
81 setContactId($(hiddenEl).val());
82 });
83 };
84
85 })(jQuery, CRM);