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 contactUrl
= CRM
.url('civicrm/ajax/rest', 'className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1');
30 var widgetEl
= $('<input type="text" />');
32 var activeContactId
= null;
33 var setContactId = function(newContactId
) {
34 if (newContactId
!= $(hiddenEl
).val()) {
35 $(hiddenEl
).val(newContactId
);
36 $(hiddenEl
).trigger('change');
38 if (activeContactId
!= newContactId
) {
39 activeContactId
= newContactId
;
41 if (activeContactId
) {
43 $(widgetEl
).css({visibility
: 'hidden'}); // don't allow input during ajax
45 url
: contactUrl
+ '&id=' + newContactId
,
47 success : function(html
){
48 var htmlText
= html
.split( '|' , 2);
49 $(widgetEl
).val(htmlText
[0]);
50 $(widgetEl
).css({visibility
: 'visible'});
54 // there is no name to lookup - just show a blank
60 $(hiddenEl
).after(widgetEl
);
62 $(widgetEl
).autocomplete(contactUrl
, {
68 }).result(function(event
, data
) {
69 activeContactId
= data
[1];
70 setContactId(activeContactId
);
71 }).bind('change blur', function() {
72 if (! $(widgetEl
).val()) {
74 setContactId(activeContactId
);
78 $(hiddenEl
).bind('change', function(){
79 setContactId($(this).val());
81 setContactId($(hiddenEl
).val());