1 // https://civicrm.org/licensing
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
6 (function($, CRM
, undefined) {
9 * @param string|object query
10 * @param string mode - optionally specify "front" or "back"
13 CRM
.url = function (path
, query
, mode
) {
14 if (typeof path
=== 'object') {
18 console
&& console
.log
&& console
.log('Warning: CRM.url called before initialization');
21 mode
= CRM
.config
&& CRM
.config
.isFrontend
? 'front' : 'back';
24 var frag
= path
.split('?');
25 var url
= tplURL
[mode
].replace("*path*", frag
[0]);
28 url
= url
.replace(/[?&]\*query\*/, '');
31 url
= url
.replace("*query*", typeof query
=== 'string' ? query
: $.param(query
));
34 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
39 // Backwards compatible with jQuery fn
41 function (p
, params
) {
42 console
&& console
.log
&& console
.log('Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
43 return CRM
.url(p
, params
);
47 $.fn
.crmURL = function () {
48 return this.each(function() {
50 this.href
= CRM
.url(this.href
);
58 CRM
.api3 = function(entity
, action
, params
, status
) {
59 if (typeof(entity
) === 'string') {
62 action
: action
.toLowerCase(),
63 json
: JSON
.stringify(params
|| {})
69 json
: JSON
.stringify(entity
)
74 url
: CRM
.url('civicrm/ajax/rest'),
77 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
80 // Default status messages
81 if (status
=== true) {
82 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
83 if (params
.action
.indexOf('get') === 0) {
84 status
.start
= ts('Loading...');
85 status
.success
= null;
88 var messages
= status
=== true ? {} : status
;
89 CRM
.status(status
, ajax
);
98 CRM
.api = function(entity
, action
, params
, options
) {
102 success: function(result
, settings
) {
105 error: function(result
, settings
) {
106 $().crmError(result
.error_message
, ts('Error'));
109 callBack: function(result
, settings
) {
110 if (result
.is_error
== 1) {
111 return settings
.error
.call(this, result
, settings
);
113 return settings
.success
.call(this, result
, settings
);
115 ajaxURL
: 'civicrm/ajax/rest'
117 action
= action
.toLowerCase();
118 // Default success handler
124 settings
.success = function() {
125 CRM
.status(ts('Saved'));
130 settings
.success = function() {
131 CRM
.status(ts('Removed'));
138 json
: JSON
.stringify(params
)
140 // Pass copy of settings into closure to preserve its value during multiple requests
143 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
146 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
147 success: function(result
) {
148 stg
.callBack
.call(stg
.context
, result
, stg
);
151 })($.extend({}, settings
, options
));
155 * Backwards compatible with jQuery fn
158 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
159 console
&& console
.log
&& console
.log('Calling crmAPI from jQuery is deprecated. Please use CRM.api() instead.');
160 return CRM
.api
.call(this, entity
, action
, params
, options
);
163 $.widget('civi.crmSnippet', {
169 _originalContent
: null,
171 isOriginalUrl: function() {
175 newUrl
= this._formatUrl(this.options
.url
),
176 oldUrl
= this._formatUrl(this._originalUrl
);
178 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
182 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
183 var arg
= v
.split('=');
184 args
[arg
[0]] = arg
[1];
186 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
187 var arg
= v
.split('=');
188 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
194 resetUrl: function() {
195 this.options
.url
= this._originalUrl
;
197 _create: function() {
198 this.element
.addClass('crm-ajax-container');
199 if (!this.element
.is('.crm-container *')) {
200 this.element
.addClass('crm-container');
202 this._handleOrderLinks();
203 // Set default if not supplied
204 this.options
.url
= this.options
.url
|| document
.location
.href
;
205 this._originalUrl
= this.options
.url
;
207 _onFailure: function(data
) {
208 this.options
.block
&& this.element
.unblock();
209 this.element
.trigger('crmAjaxFail', data
);
210 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
212 _onError: function(data
) {
213 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
214 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
215 this.element
.dialog('close');
218 _formatUrl: function(url
) {
220 url
= url
.split('#')[0];
221 // Add snippet argument to url
222 if (url
.search(/[&?]snippet=/) < 0) {
223 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
225 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
229 // Hack to deal with civicrm legacy sort functionality
230 _handleOrderLinks: function() {
232 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
233 that
.options
.block
&& that
.element
.block();
234 $.getJSON(that
._formatUrl(this.href
)).done(function() {
237 e
.stopImmediatePropagation();
241 refresh: function() {
243 var url
= this._formatUrl(this.options
.url
);
244 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
245 if (this._originalContent
=== null) {
246 this._originalContent
= this.element
.contents().detach();
248 this.options
.block
&& this.element
.block();
249 $.getJSON(url
, function(data
) {
250 that
.options
.block
&& that
.element
.unblock();
251 if (!$.isPlainObject(data
)) {
252 that
._onFailure(data
);
255 if (data
.status
=== 'error') {
260 that
.element
.trigger('crmBeforeLoad', data
).html(data
.content
);
261 that
._handleOrderLinks();
262 that
.element
.trigger('crmLoad', data
);
263 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
268 _destroy: function() {
269 this.element
.removeClass('crm-ajax-container');
270 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
271 if (this._originalContent
!== null) {
272 this.element
.empty().append(this._originalContent
);
278 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
280 CRM
.loadPage = function(url
, options
) {
282 target
: '#crm-ajax-dialog-' + (dialogCount
++),
285 if (!options
|| !options
.target
) {
292 options
&& $.extend(true, settings
, options
);
295 if (settings
.dialog
) {
296 // HACK: jQuery UI doesn't support relative height
297 if (typeof settings
.dialog
.height
=== 'string' && settings
.dialog
.height
.indexOf('%') > 0) {
298 settings
.dialog
.height
= parseInt($(window
).height() * (parseFloat(settings
.dialog
.height
)/100), 10);
300 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
302 .on('dialogclose', function() {
303 if ($(this).attr('data-unsaved-changes') !== 'true') {
304 $(this).crmSnippet('destroy').dialog('destroy').remove();
307 .on('crmLoad', function(e
, data
) {
309 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
310 $(this).dialog('option', 'title', data
.title
);
312 // Adjust height to fit content (small delay to allow elements to render)
313 window
.setTimeout(function() {
314 var currentHeight
= $(settings
.target
).parent().outerHeight(),
315 padding
= currentHeight
- $(settings
.target
).height(),
316 newHeight
= $(settings
.target
).prop('scrollHeight') + padding
,
317 menuHeight
= $('#civicrm-menu').outerHeight(),
318 maxHeight
= $(window
).height() - menuHeight
;
319 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
320 if (newHeight
> (currentHeight
+ 15)) {
321 $(settings
.target
).dialog('option', {
322 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
329 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
330 return $(settings
.target
);
332 CRM
.loadForm = function(url
, options
) {
333 var formErrors
= [], settings
= {
338 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
339 cancelButton
: '.cancel',
340 openInline
: 'a.open-inline, a.button, a.action-item',
341 onCancel: function(event
) {}
344 // Move options that belong to crmForm. Others will be passed through to crmSnippet
345 options
&& $.each(options
, function(key
, value
) {
346 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
347 settings
.crmForm
[key
] = value
;
350 settings
[key
] = value
;
354 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
356 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
357 function cancelAction() {
358 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
359 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
361 var id
= widget
.attr('id') + '-unsaved-alert',
362 title
= widget
.dialog('option', 'title'),
363 alert
= CRM
.alert('<p>' + ts('%1 has not been saved.', {1: title
}) + '</p><p><a href="#" id="' + id
+ '">' + ts('Restore') + '</a></p>', ts('Unsaved Changes'), 'alert unsaved-dialog', {expires
: 60000});
364 $('#' + id
).button({icons
: {primary
: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e
) {
365 widget
.attr('data-unsaved-changes', 'false').dialog('open');
371 widget
.data('uiDialog') && widget
.on('dialogbeforeclose', function(e
) {
372 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
373 if (e
.originalEvent
) {
378 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
379 var $el
= $(this).attr('data-unsaved-changes', 'false'),
380 settings
= $el
.crmSnippet('option', 'crmForm');
381 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(e
) {
383 var returnVal
= settings
.onCancel
.call($el
, e
);
384 if (returnVal
!== false) {
385 $el
.trigger('crmFormCancel', e
);
386 if ($el
.data('uiDialog') && settings
.autoClose
) {
390 else if (!settings
.autoClose
) {
391 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
395 if (settings
.validate
) {
396 $("form", this).crmValidate();
398 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
399 url
: data
.url
.replace(/reset=1[&]?/, ''),
401 success: function(response
) {
402 if (response
.content
=== undefined) {
403 $el
.trigger('crmFormSuccess', response
);
404 // Reset form for e.g. "save and new"
405 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
406 // Force reset of original url
407 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
408 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
410 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
411 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
414 else if (settings
.autoClose
=== false) {
415 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
419 $el
.crmSnippet('option', 'block') && $el
.unblock();
420 response
.url
= data
.url
;
421 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
422 if (response
.status
=== 'form_error') {
424 $el
.trigger('crmFormError', response
);
425 $.each(response
.errors
|| [], function(formElement
, msg
) {
426 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
431 beforeSerialize: function(form
, options
) {
432 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
433 $.each(CKEDITOR
.instances
, function() {
434 this.updateElement
&& this.updateElement();
438 beforeSubmit: function(submission
) {
439 $.each(formErrors
, function() {
440 this && this.close
&& this.close();
442 $el
.crmSnippet('option', 'block') && $el
.block();
443 $el
.trigger('crmFormSubmit', submission
);
445 }, settings
.ajaxForm
));
446 if (settings
.openInline
) {
447 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
448 $(settings
.openInline
, this).not(exclude
+ ', .crm-popup').click(function(event
) {
449 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
453 // Show form buttons as part of the dialog
454 if ($el
.data('uiDialog')) {
455 var buttons
= [], added
= [];
456 $('input.crm-form-submit, a.button', $el
).each(function() {
458 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
459 identifier
= $el
.attr('name') || $el
.attr('href');
460 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
461 var button
= {text
: label
, click: function () {
464 if ($el
.find('.icon').length
) {
465 button
.icons
= {primary
: $el
.find('.icon').attr('class')};
467 button
.icons
= {primary
: $el
.hasClass('cancel') ? 'ui-icon-close' : 'ui-icon-check'};
468 if (identifier
.substr(identifier
.length
-4) === '_new') {
469 button
.icons
.secondary
= 'ui-icon-plus';
472 buttons
.push(button
);
473 added
.push(identifier
);
475 $el
.hide().parents('.crm-button, .crm-submit-buttons, .action-link').hide();
477 $el
.dialog('option', 'buttons', buttons
);
479 // Allow a button to prevent ajax submit
480 $('input[data-no-ajax-submit=true]').click(function() {
481 $(this).closest('form').ajaxFormUnbind();
483 // For convenience, focus the first field
484 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
489 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
491 CRM
.popup = function(e
) {
492 var $el
= $(this).first(),
493 url
= $el
.attr('href'),
494 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
495 settings
= $el
.data('popup-settings') || {},
497 settings
.dialog
= settings
.dialog
|| {};
498 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
501 // Sized based on css class
502 if ($el
.hasClass('small-popup')) {
503 settings
.dialog
.width
= 400;
504 settings
.dialog
.height
= 300;
506 else if ($el
.hasClass('medium-popup')) {
507 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
509 else if ($el
.hasClass('huge-popup')) {
510 settings
.dialog
.height
= '90%';
512 var dialog
= popup(url
, settings
);
513 // Trigger events from the dialog on the original link element
514 $el
.trigger('crmPopupOpen', [dialog
]);
515 // Listen for success events and buffer them so we only trigger once
516 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
519 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
521 $el
.trigger('crmPopupFormSuccess', [dialog
, data
]);
523 $el
.trigger('crmPopupClose', [dialog
, data
]);
528 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
529 * @param e {event|selector}
531 CRM
.refreshParent = function(e
) {
532 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
533 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
534 $table
= $el
.closest('.dataTable');
535 // Call native refresh method on ajax datatables
536 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
537 // Refresh ALL datatables - needed for contact relationship tab
538 $.each($.fn
.dataTable
.fnTables(), function() {
539 $(this).dataTable().fnSettings().sAjaxSource
&& $(this).unblock().dataTable().fnDraw();
542 // Otherwise refresh the nearest crmSnippet
544 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
550 .on('click', 'a.crm-popup', CRM
.popup
)
551 // Close unsaved dialog messages
552 .on('dialogopen', function(e
) {
553 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
555 // Destroy old unsaved dialog
556 .on('dialogcreate', function(e
) {
557 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();