4 * Setup a contact widget for use in CRUD forms. The form element stores a contact ID
5 * but displays a name/label.
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());
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.
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.
26 $.fn
.crmContactField = function() {
27 return this.each(function(){
28 var urlParams
= 'className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1';
30 var widgetEl
= $('<input type="text" />');
32 var activeContactId
= null;
33 // For organization autocomplete
34 if($(this).attr('autocompleteType') == 'org') {
35 var urlParams
= urlParams
+ '&org=1';
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');
43 if (activeContactId
!= newContactId
) {
44 activeContactId
= newContactId
;
46 if (activeContactId
) {
48 $(widgetEl
).css({visibility
: 'hidden'}); // don't allow input during ajax
50 url
: contactUrl
+ '&id=' + newContactId
,
52 success : function(html
){
53 var htmlText
= html
.split( '|' , 2);
54 $(widgetEl
).val(htmlText
[0]);
55 $(widgetEl
).css({visibility
: 'visible'});
59 // there is no name to lookup - just show a blank
65 $(hiddenEl
).after(widgetEl
);
67 $(widgetEl
).autocomplete(contactUrl
, {
73 }).result(function(event
, data
) {
74 activeContactId
= data
[1];
75 setContactId(activeContactId
);
76 }).bind('change blur', function() {
77 if (! $(widgetEl
).val()) {
79 setContactId(activeContactId
);
83 $(hiddenEl
).bind('change', function(){
84 setContactId($(this).val());
86 setContactId($(hiddenEl
).val());