fixed generated data for CRM-15934
[civicrm-core.git] / js / crm.ajax.js
1 // https://civicrm.org/licensing
2 /**
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
5 */
6 (function($, CRM, undefined) {
7 /**
8 * @param string path
9 * @param string|object query
10 * @param string mode - optionally specify "front" or "back"
11 */
12 var tplURL;
13 CRM.url = function (path, query, mode) {
14 if (typeof path === 'object') {
15 tplURL = path;
16 return path;
17 }
18 if (!tplURL) {
19 CRM.console('error', 'Error: CRM.url called before initialization');
20 }
21 if (!mode) {
22 mode = CRM.config && CRM.config.isFrontend ? 'front' : 'back';
23 }
24 query = query || '';
25 var frag = path.split('?');
26 var url = tplURL[mode].replace("*path*", frag[0]);
27
28 if (!query) {
29 url = url.replace(/[?&]\*query\*/, '');
30 }
31 else {
32 url = url.replace("*query*", typeof query === 'string' ? query : $.param(query));
33 }
34 if (frag[1]) {
35 url += (url.indexOf('?') < 0 ? '?' : '&') + frag[1];
36 }
37 return url;
38 };
39
40 // @deprecated
41 $.extend ({'crmURL':
42 function (p, params) {
43 CRM.console('warn', 'Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
44 return CRM.url(p, params);
45 }
46 });
47
48 $.fn.crmURL = function () {
49 return this.each(function() {
50 if (this.href) {
51 this.href = CRM.url(this.href);
52 }
53 });
54 };
55
56 /**
57 * AJAX api
58 */
59 CRM.api3 = function(entity, action, params, status) {
60 if (typeof(entity) === 'string') {
61 params = {
62 entity: entity,
63 action: action.toLowerCase(),
64 json: JSON.stringify(params || {})
65 };
66 } else {
67 params = {
68 entity: 'api3',
69 action: 'call',
70 json: JSON.stringify(entity)
71 };
72 status = action;
73 }
74 var ajax = $.ajax({
75 url: CRM.url('civicrm/ajax/rest'),
76 dataType: 'json',
77 data: params,
78 type: params.action.indexOf('get') < 0 ? 'POST' : 'GET'
79 });
80 if (status) {
81 // Default status messages
82 if (status === true) {
83 status = {success: params.action === 'delete' ? ts('Removed') : ts('Saved')};
84 if (params.action.indexOf('get') === 0) {
85 status.start = ts('Loading...');
86 status.success = null;
87 }
88 }
89 var messages = status === true ? {} : status;
90 CRM.status(status, ajax);
91 }
92 return ajax;
93 };
94
95 /**
96 * @deprecated
97 * AJAX api
98 */
99 CRM.api = function(entity, action, params, options) {
100 // Default settings
101 var settings = {
102 context: null,
103 success: function(result, settings) {
104 return true;
105 },
106 error: function(result, settings) {
107 $().crmError(result.error_message, ts('Error'));
108 return false;
109 },
110 callBack: function(result, settings) {
111 if (result.is_error == 1) {
112 return settings.error.call(this, result, settings);
113 }
114 return settings.success.call(this, result, settings);
115 },
116 ajaxURL: 'civicrm/ajax/rest'
117 };
118 action = action.toLowerCase();
119 // Default success handler
120 switch (action) {
121 case "update":
122 case "create":
123 case "setvalue":
124 case "replace":
125 settings.success = function() {
126 CRM.status(ts('Saved'));
127 return true;
128 };
129 break;
130 case "delete":
131 settings.success = function() {
132 CRM.status(ts('Removed'));
133 return true;
134 };
135 }
136 params = {
137 entity: entity,
138 action: action,
139 json: JSON.stringify(params)
140 };
141 // Pass copy of settings into closure to preserve its value during multiple requests
142 (function(stg) {
143 $.ajax({
144 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
145 dataType: 'json',
146 data: params,
147 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
148 success: function(result) {
149 stg.callBack.call(stg.context, result, stg);
150 }
151 });
152 })($.extend({}, settings, options));
153 };
154
155 /**
156 * Backwards compatible with jQuery fn
157 * @deprecated
158 */
159 $.fn.crmAPI = function(entity, action, params, options) {
160 CRM.console('warn', 'Calling crmAPI from jQuery is deprecated. Please use CRM.api3() instead.');
161 return CRM.api.call(this, entity, action, params, options);
162 };
163
164 $.widget('civi.crmSnippet', {
165 options: {
166 url: null,
167 block: true,
168 crmForm: null
169 },
170 _originalContent: null,
171 _originalUrl: null,
172 isOriginalUrl: function() {
173 var
174 args = {},
175 same = true,
176 newUrl = this._formatUrl(this.options.url),
177 oldUrl = this._formatUrl(this._originalUrl);
178 // Compare path
179 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
180 return false;
181 }
182 // Compare arguments
183 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
184 var arg = v.split('=');
185 args[arg[0]] = arg[1];
186 });
187 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
188 var arg = v.split('=');
189 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
190 same = false;
191 }
192 });
193 return same;
194 },
195 resetUrl: function() {
196 this.options.url = this._originalUrl;
197 },
198 _create: function() {
199 this.element.addClass('crm-ajax-container');
200 if (!this.element.is('.crm-container *')) {
201 this.element.addClass('crm-container');
202 }
203 this._handleOrderLinks();
204 // Set default if not supplied
205 this.options.url = this.options.url || document.location.href;
206 this._originalUrl = this.options.url;
207 },
208 _onFailure: function(data, status) {
209 var msg, title = ts('Network Error');
210 if (this.options.block) this.element.unblock();
211 this.element.trigger('crmAjaxFail', data);
212 switch (status) {
213 case 'Forbidden':
214 title = ts('Access Denied');
215 msg = ts('Ensure you are still logged in and have permission to access this feature.');
216 break;
217 default:
218 msg = ts('Unable to reach the server. Please refresh this page in your browser and try again.');
219 }
220 CRM.alert(msg, title, 'error');
221 },
222 _onError: function(data) {
223 this.element.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data);
224 if (this.options.crmForm && this.options.crmForm.autoClose && this.element.data('uiDialog')) {
225 this.element.dialog('close');
226 }
227 },
228 _formatUrl: function(url) {
229 // Strip hash
230 url = url.split('#')[0];
231 // Add snippet argument to url
232 if (url.search(/[&?]snippet=/) < 0) {
233 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
234 } else {
235 url = url.replace(/snippet=[^&]*/, 'snippet=json');
236 }
237 return url;
238 },
239 // Hack to deal with civicrm legacy sort functionality
240 _handleOrderLinks: function() {
241 var that = this;
242 $('a.crm-weight-arrow', that.element).click(function(e) {
243 if (that.options.block) that.element.block();
244 $.getJSON(that._formatUrl(this.href)).done(function() {
245 that.refresh();
246 });
247 e.stopImmediatePropagation();
248 return false;
249 });
250 },
251 refresh: function() {
252 var that = this;
253 var url = this._formatUrl(this.options.url);
254 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
255 if (this._originalContent === null) {
256 this._originalContent = this.element.contents().detach();
257 }
258 if (this.options.block) this.element.block();
259 $.getJSON(url, function(data) {
260 if (that.options.block) that.element.unblock();
261 if (!$.isPlainObject(data)) {
262 that._onFailure(data);
263 return;
264 }
265 if (data.status === 'error') {
266 that._onError(data);
267 return;
268 }
269 data.url = url;
270 that.element.trigger('crmUnload').trigger('crmBeforeLoad', data);
271 that._beforeRemovingContent();
272 that.element.html(data.content);
273 that._handleOrderLinks();
274 that.element.trigger('crmLoad', data);
275 if (that.options.crmForm) that.element.trigger('crmFormLoad', data);
276 }).fail(function(data, msg, status) {
277 that._onFailure(data, status);
278 });
279 },
280 // Perform any cleanup needed before removing/replacing content
281 _beforeRemovingContent: function() {
282 var that = this;
283 if (window.tinyMCE && tinyMCE.editors) {
284 $.each(tinyMCE.editors, function(k) {
285 if ($.contains(that.element[0], this.getElement())) {
286 this.remove();
287 }
288 });
289 }
290 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
291 },
292 _destroy: function() {
293 this.element.removeClass('crm-ajax-container').trigger('crmUnload');
294 this._beforeRemovingContent();
295 if (this._originalContent !== null) {
296 this.element.empty().append(this._originalContent);
297 }
298 }
299 });
300
301 var dialogCount = 0,
302 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
303
304 CRM.loadPage = function(url, options) {
305 var settings = {
306 target: '#crm-ajax-dialog-' + (dialogCount++),
307 dialog: (options && options.target) ? false : {}
308 };
309 if (options) $.extend(true, settings, options);
310 settings.url = url;
311 // Create new dialog
312 if (settings.dialog) {
313 settings.dialog = CRM.utils.adjustDialogDefaults(settings.dialog);
314 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
315 $(settings.target)
316 .on('dialogclose', function() {
317 if ($(this).attr('data-unsaved-changes') !== 'true') {
318 $(this).crmSnippet('destroy').dialog('destroy').remove();
319 }
320 })
321 .on('crmLoad', function(e, data) {
322 // Set title
323 if (e.target === $(settings.target)[0] && data && !settings.dialog.title && data.title) {
324 $(this).dialog('option', 'title', data.title);
325 }
326 });
327 }
328 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
329 return $(settings.target);
330 };
331 CRM.loadForm = function(url, options) {
332 var formErrors = [], settings = {
333 crmForm: {
334 ajaxForm: {},
335 autoClose: true,
336 validate: true,
337 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
338 cancelButton: '.cancel',
339 openInline: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
340 onCancel: function(event) {}
341 }
342 };
343 // Move options that belong to crmForm. Others will be passed through to crmSnippet
344 if (options) $.each(options, function(key, value) {
345 if (typeof(settings.crmForm[key]) !== 'undefined') {
346 settings.crmForm[key] = value;
347 }
348 else {
349 settings[key] = value;
350 }
351 });
352
353 var widget = CRM.loadPage(url, settings).off('.crmForm');
354
355 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
356 function cancelAction() {
357 var dirty = CRM.utils.initialValueChanged($('form:not([data-warn-changes=false])', widget));
358 widget.attr('data-unsaved-changes', dirty ? 'true' : 'false');
359 if (dirty) {
360 var id = widget.attr('id') + '-unsaved-alert',
361 title = widget.dialog('option', 'title'),
362 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});
363 $('#' + id).button({icons: {primary: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e) {
364 widget.attr('data-unsaved-changes', 'false').dialog('open');
365 e.preventDefault();
366 });
367 }
368 }
369
370 if (widget.data('uiDialog')) widget.on('dialogbeforeclose', function(e) {
371 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
372 if (e.originalEvent) {
373 cancelAction();
374 }
375 });
376
377 widget.on('crmFormLoad.crmForm', function(event, data) {
378 var $el = $(this).attr('data-unsaved-changes', 'false'),
379 settings = $el.crmSnippet('option', 'crmForm');
380 if (settings.cancelButton) $(settings.cancelButton, this).click(function(e) {
381 e.preventDefault();
382 var returnVal = settings.onCancel.call($el, e);
383 if (returnVal !== false) {
384 $el.trigger('crmFormCancel', e);
385 if ($el.data('uiDialog') && settings.autoClose) {
386 cancelAction();
387 $el.dialog('close');
388 }
389 else if (!settings.autoClose) {
390 $el.crmSnippet('resetUrl').crmSnippet('refresh');
391 }
392 }
393 });
394 if (settings.validate) {
395 $("form", this).crmValidate();
396 }
397 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
398 url: data.url.replace(/reset=1[&]?/, ''),
399 dataType: 'json',
400 success: function(response) {
401 if (response.content === undefined) {
402 $el.trigger('crmFormSuccess', response);
403 // Reset form for e.g. "save and new"
404 if (response.userContext && (response.status === 'redirect' || (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0))) {
405 // Force reset of original url
406 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
407 $el.crmSnippet('resetUrl').crmSnippet('refresh');
408 }
409 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
410 else if ($el.data('uiDialog') && (settings.autoClose || response.action === 8)) {
411 $el.dialog('close');
412 }
413 else if (settings.autoClose === false) {
414 $el.crmSnippet('resetUrl').crmSnippet('refresh');
415 }
416 }
417 else {
418 if ($el.crmSnippet('option', 'block')) $el.unblock();
419 response.url = data.url;
420 $el.html(response.content).trigger('crmLoad', response).trigger('crmFormLoad', response);
421 if (response.status === 'form_error') {
422 formErrors = [];
423 $el.trigger('crmFormError', response);
424 $.each(response.errors || [], function(formElement, msg) {
425 formErrors.push($('[name="'+formElement+'"]', $el).crmError(msg));
426 });
427 }
428 }
429 },
430 beforeSerialize: function(form, options) {
431 if (window.CKEDITOR && window.CKEDITOR.instances) {
432 $.each(CKEDITOR.instances, function() {
433 if (this.updateElement) this.updateElement();
434 });
435 }
436 if (window.tinyMCE && tinyMCE.editors) {
437 $.each(tinyMCE.editors, function() {
438 this.save();
439 });
440 }
441 },
442 beforeSubmit: function(submission) {
443 $.each(formErrors, function() {
444 if (this && this.close) this.close();
445 });
446 if ($el.crmSnippet('option', 'block')) $el.block();
447 $el.trigger('crmFormSubmit', submission);
448 }
449 }, settings.ajaxForm));
450 if (settings.openInline) {
451 settings.autoClose = $el.crmSnippet('isOriginalUrl');
452 $(settings.openInline, this).not(exclude + ', .crm-popup').click(function(event) {
453 if ($(this).hasClass('open-inline-noreturn')) {
454 // Force reset of original url
455 $el.data('civiCrmSnippet')._originalUrl = $(this).attr('href');
456 }
457 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
458 return false;
459 });
460 }
461 // Show form buttons as part of the dialog
462 if ($el.data('uiDialog')) {
463 var buttonContainers = '.crm-submit-buttons, .action-link',
464 buttons = [],
465 added = [];
466 $(buttonContainers, $el).find('input.crm-form-submit, a.button').each(function() {
467 var $el = $(this),
468 label = $el.is('input') ? $el.attr('value') : $el.text(),
469 identifier = $el.attr('name') || $el.attr('href');
470 if (!identifier || identifier === '#' || $.inArray(identifier, added) < 0) {
471 var $icon = $el.find('.icon'),
472 button = {'data-identifier': identifier, text: label, click: function() {
473 $el[0].click();
474 }};
475 if ($icon.length) {
476 button.icons = {primary: $icon.attr('class')};
477 } else {
478 var action = $el.attr('crm-icon') || ($el.hasClass('cancel') ? 'close' : 'check');
479 button.icons = {primary: 'ui-icon-' + action};
480 }
481 buttons.push(button);
482 added.push(identifier);
483 }
484 // display:none causes the form to not submit when pressing "enter"
485 $el.parents(buttonContainers).css({height: 0, padding: 0, margin: 0, overflow: 'hidden'}).find('.crm-button-icon').hide();
486 });
487 $el.dialog('option', 'buttons', buttons);
488 }
489 // Allow a button to prevent ajax submit
490 $('input[data-no-ajax-submit=true]').click(function() {
491 $(this).closest('form').ajaxFormUnbind();
492 });
493 // For convenience, focus the first field
494 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
495 });
496 return widget;
497 };
498 /**
499 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
500 */
501 CRM.popup = function(e) {
502 var $el = $(this).first(),
503 url = $el.attr('href'),
504 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
505 settings = $el.data('popup-settings') || {},
506 formSuccess = false;
507 settings.dialog = settings.dialog || {};
508 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude)) {
509 return;
510 }
511 // Sized based on css class
512 if ($el.hasClass('small-popup')) {
513 settings.dialog.width = 400;
514 settings.dialog.height = 300;
515 }
516 else if ($el.hasClass('medium-popup')) {
517 settings.dialog.width = settings.dialog.height = '50%';
518 }
519 var dialog = popup(url, settings);
520 // Trigger events from the dialog on the original link element
521 $el.trigger('crmPopupOpen', [dialog]);
522 // Listen for success events and buffer them so we only trigger once
523 dialog.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
524 formSuccess = true;
525 });
526 dialog.on('dialogclose.crmPopup', function(e, data) {
527 if (formSuccess) {
528 $el.trigger('crmPopupFormSuccess', [dialog, data]);
529 }
530 $el.trigger('crmPopupClose', [dialog, data]);
531 });
532 e.preventDefault();
533 };
534 /**
535 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
536 * @param e {event|selector}
537 */
538 CRM.refreshParent = function(e) {
539 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
540 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
541 $table = $el.closest('.dataTable');
542 // Call native refresh method on ajax datatables
543 if ($table.length && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
544 // Refresh ALL datatables - needed for contact relationship tab
545 $.each($.fn.dataTable.fnTables(), function() {
546 if ($(this).dataTable().fnSettings().sAjaxSource) $(this).unblock().dataTable().fnDraw();
547 });
548 }
549 // Otherwise refresh the nearest crmSnippet
550 else {
551 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
552 }
553 };
554
555 $(function($) {
556 $('body')
557 .on('click', 'a.crm-popup', CRM.popup)
558 // Close unsaved dialog messages
559 .on('dialogopen', function(e) {
560 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
561 })
562 // Destroy old unsaved dialog
563 .on('dialogcreate', function(e) {
564 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
565 })
566 // Auto-resize dialogs when loading content
567 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e) {
568 var
569 $wrapper = $(this),
570 $dialog = $wrapper.children('.ui-dialog-content');
571 // small delay to allow contents to render
572 window.setTimeout(function() {
573 var currentHeight = $wrapper.outerHeight(),
574 padding = currentHeight - $dialog.height(),
575 newHeight = $dialog.prop('scrollHeight') + padding,
576 menuHeight = $('#civicrm-menu').outerHeight(),
577 maxHeight = $(window).height() - menuHeight;
578 newHeight = newHeight > maxHeight ? maxHeight : newHeight;
579 if (newHeight > (currentHeight + 15)) {
580 $dialog.dialog('option', {
581 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
582 height: newHeight
583 });
584 }
585 }, 500);
586 });
587 });
588
589 }(jQuery, CRM));