7f2ec390bfc554f52abfac6d18928237b4044c00
1 (function($, _
, undefined) {
10 fieldTpl
= _
.template($('#api-param-tpl').html()),
11 optionsTpl
= _
.template($('#api-options-tpl').html()),
12 returnTpl
= _
.template($('#api-return-tpl').html()),
13 chainTpl
= _
.template($('#api-chain-tpl').html());
16 * Call prettyPrint function if it successfully loaded from the cdn
18 function prettyPrint() {
19 if (window
.prettyPrint
) {
28 function addField(name
) {
29 $('#api-params').append($(fieldTpl({name
: name
|| ''})));
30 var $row
= $('tr:last-child', '#api-params');
31 $('.api-param-name', $row
).crmSelect2({
32 data
: fields
.concat({id
: '-', text
: ts('Other') + '...'})
37 * Add a new "options" row
40 function addOptionField(name
) {
41 if ($('.api-options-row', '#api-params').length
) {
42 $('.api-options-row:last', '#api-params').after($(optionsTpl({})));
44 $('#api-params').append($(optionsTpl({})));
46 var $row
= $('.api-options-row:last', '#api-params');
47 $('.api-option-name', $row
).crmSelect2({data
: [
48 {id
: 'limit', text
: 'limit'},
49 {id
: 'offset', text
: 'offset'},
50 {id
: 'sort', text
: 'sort'},
51 {id
: 'metadata', text
: 'metadata'},
52 {id
: '-', text
: ts('Other') + '...'}
57 * Add an "api chain" row
59 function addChainField() {
60 $('#api-params').append($(chainTpl({})));
61 var $row
= $('tr:last-child', '#api-params');
62 $('.api-chain-entity', $row
).crmSelect2({
63 formatSelection: function(item
) {
64 return '<span class="icon ui-icon-link"></span> API ' + item
.text
;
66 placeholder
: '<span class="icon ui-icon-link"></span> ' + ts('Entity'),
67 escapeMarkup: function(m
) {return m
}
72 * Fetch fields for entity+action
74 function getFields() {
78 // Special case for getfields
79 if (action
=== 'getfields') {
84 options
.api_action
= [];
85 $('option', '#api-action').each(function() {
87 options
.api_action
.push({key
: this.value
, value
: $(this).text()});
90 showFields(['api_action']);
93 CRM
.api3(entity
, 'getFields', {'api_action': action
, sequential
: 1, options
: {get_options
: 'all'}}).done(function(data
) {
94 _
.each(data
.values
, function(field
) {
98 text
: field
.title
|| field
.name
,
99 required
: field
['api.required'] || false
101 if (field
['api.required']) {
102 required
.push(field
.name
);
105 options
[field
.name
] = field
.options
;
109 showFields(required
);
110 if (action
=== 'get' || action
=== 'getsingle') {
117 * For "get" actions show the "return" options
119 function showReturn() {
120 $('#api-params').prepend($(returnTpl({})));
121 $('#api-return-value').crmSelect2({data
: fields
, multiple
: true});
125 * Fetch actions for entity
127 function getActions() {
129 CRM
.api3(entity
, 'getactions').done(function(data
) {
130 actions
= data
.values
|| ['get'];
140 * Called after getActions to populate action list
143 function populateActions(el
) {
144 var val
= $('#api-action').val();
145 $('#api-action').select2({
146 data
: _
.transform(actions
, function(ret
, item
) {ret
.push({text
: item
, id
: item
})})
148 // If previously selected action is not available, set it to 'get' if possible
149 if (_
.indexOf(actions
, val
) < 0) {
150 $('#api-action').select2('val', _
.indexOf(actions
, 'get') < 0 ? actions
[0] : 'get', true);
155 * Called after getfields to show buttons and required fields
158 function showFields(required
) {
159 $('#api-params').empty();
160 $('#api-param-buttons').show();
161 if (required
.length
) {
162 _
.each(required
, addField
);
169 * Add/remove option list for selected field's pseudoconstant
171 function toggleOptions() {
172 var name
= $(this).val(),
173 $valField
= $(this).closest('tr').find('.api-param-value');
175 $valField
.val('').select2({
177 data
: _
.transform(options
[name
], function(result
, option
) {
178 result
.push({id
: option
.key
, text
: option
.value
});
182 else if ($valField
.data('select2')) {
183 $valField
.select2('destroy');
188 * Attempt to parse a string into a value of the intended type
190 * @param makeArray bool
192 function evaluate(val
, makeArray
) {
197 var first
= val
.charAt(0),
198 last
= val
.slice(-1);
200 if (val
=== 'true' || val
=== 'false' || val
=== 'null' || !isNaN(val
)) {
204 if ((first
=== '"' || first
=== "'") && last
=== first
) {
205 return val
.slice(1, -1);
208 if ((first
=== '[' && last
=== ']') || (first
=== '{' && last
=== '}')) {
209 return eval('(' + val
+ ')');
211 // Transform csv to array
212 if (makeArray
&& val
.indexOf(',') > 0) {
213 return val
.split(',');
215 // Ok ok it's really a string
218 // If eval crashed return undefined
224 * Format value to look like php code
227 function phpFormat(val
) {
229 if ($.isPlainObject(val
)) {
230 $.each(val
, function(k
, v
) {
231 ret
+= (ret
? ', ' : '') + "'" + k
+ "' => " + phpFormat(v
);
233 return 'array(' + ret
+ ')';
235 if ($.isArray(val
)) {
236 $.each(val
, function(k
, v
) {
237 ret
+= (ret
? ', ' : '') + phpFormat(v
);
239 return 'array(' + ret
+ ')';
241 return JSON
.stringify(val
).replace(/\$/g, '\\$');
245 * Smarty doesn't support array literals so we provide a stub
248 function smartyFormat(js
, key
) {
249 if (js
.indexOf('[') > -1 || js
.indexOf('{') > -1) {
251 return '$' + key
.replace(/[. -]/g, '_');
257 * Create the params array from user input
260 function buildParams(e
) {
262 $('.api-param-checkbox:checked').each(function() {
263 params
[this.name
] = 1;
265 $('input.api-param-value, input.api-option-value').each(function() {
266 var $row
= $(this).closest('tr'),
267 val
= evaluate($(this).val(), $(this).is('.select2-offscreen')),
268 name
= $('input.api-param-name', $row
).val(),
269 op
= $('select.api-param-op', $row
).val() || '=';
271 // Ignore blank values for the return field
272 if ($(this).is('#api-return-value') && !val
) {
275 // Special syntax for api chaining
276 if (!name
&& $('select.api-chain-entity', $row
).val()) {
277 name
= 'api.' + $('select.api-chain-entity', $row
).val() + '.' + $('select.api-chain-action', $row
).val();
279 // Special handling for options
280 if ($(this).is('.api-option-value')) {
281 op
= $('input.api-option-name', $row
).val();
286 if (name
&& val
!== undefined) {
287 params
[name
] = op
=== '=' ? val
: (params
[name
] || {});
289 params
[name
][op
] = val
;
291 if ($(this).hasClass('crm-error')) {
295 else if (name
&& (!e
|| e
.type
!== 'keyup')) {
299 if (entity
&& action
) {
304 function setError(el
) {
305 if (!$(el
).hasClass('crm-error')) {
306 var msg
= ts('Syntax error: input should be valid JSON or a quoted string.');
308 .addClass('crm-error')
311 .before('<div class="icon red-icon ui-icon-alert" title="'+msg
+'"/>')
316 function clearError(el
) {
318 .removeClass('crm-error')
322 .siblings('.ui-icon-alert').remove();
325 function formatQuery() {
327 smarty
: "{crmAPI var='result' entity='" + entity
+ "' action='" + action
+ "'",
328 php
: "$result = civicrm_api3('" + entity
+ "', '" + action
+ "'",
329 json
: "CRM.api3('" + entity
+ "', '" + action
+ "'",
330 drush
: "drush cvapi " + entity
+ '.' + action
+ ' ',
331 wpcli
: "wp cv api " + entity
+ '.' + action
+ ' ',
332 rest
: CRM
.config
.resourceBase
+ "extern/rest.php?entity=" + entity
+ "&action=" + action
+ "&json=" + JSON
.stringify(params
) + "&api_key=yoursitekey&key=yourkey"
335 $.each(params
, function(key
, value
) {
336 var js
= JSON
.stringify(value
);
338 q
.php
+= ", array(\n";
343 q
.php
+= " '" + key
+ "' => " + phpFormat(value
) + ",\n";
344 q
.json
+= " \"" + key
+ '": ' + js
;
345 q
.smarty
+= ' ' + key
+ '=' + smartyFormat(js
, key
);
346 q
.drush
+= key
+ '=' + js
+ ' ';
347 q
.wpcli
+= key
+ '=' + js
+ ' ';
354 q
.json
+= ").done(function(result) {\n // do something\n});";
355 q
.smarty
+= "}\n{foreach from=$result.values item=" + entity
.toLowerCase() + "}\n {$" + entity
.toLowerCase() + ".some_field}\n{/foreach}";
356 if (action
.indexOf('get') < 0) {
357 q
.smarty
= '{* Smarty API only works with get actions *}';
358 } else if (smartyStub
) {
359 q
.smarty
= "{* Smarty does not have a syntax for array literals; assign complex variables from php *}\n" + q
.smarty
;
361 $.each(q
, function(type
, val
) {
362 $('#api-' + type
).removeClass('prettyprinted').text(val
);
369 if (!entity
|| !action
) {
370 alert(ts('Select an entity.'));
373 if (action
.indexOf('get') < 0 && action
!= 'check') {
374 var msg
= action
=== 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
375 CRM
.confirm({title
: ts('Confirm %1', {1: action
}), message
: msg
}).on('crmConfirm:yes', execute
);
382 $('#api-result').html('<div class="crm-loading-element"></div>');
384 url
: CRM
.url('civicrm/ajax/rest'),
389 json
: JSON
.stringify(params
)
391 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
393 }).done(function(text
) {
394 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text
);
399 $(document
).ready(function() {
400 $('form#api-explorer')
401 .on('change', '#api-entity, #api-action', function() {
402 entity
= $('#api-entity').val();
403 if ($(this).is('#api-entity')) {
406 action
= $('#api-action').val();
407 if (entity
&& action
) {
408 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
409 $('#api-params-table thead').show();
413 $('#api-params, #api-generated pre').empty();
414 $('#api-param-buttons, #api-params-table thead').hide();
417 .on('change keyup', 'input.api-input, #api-params select', buildParams
)
418 .on('submit', submit
);
420 .on('change', '.api-param-name', toggleOptions
)
421 .on('change', '.api-param-name, .api-option-name', function() {
422 if ($(this).val() === '-') {
423 $(this).select2('destroy');
424 $(this).val('').focus();
427 .on('click', '.api-param-remove', function(e
) {
429 $(this).closest('tr').remove();
432 $('#api-params-add').on('click', function(e
) {
436 $('#api-option-add').on('click', function(e
) {
440 $('#api-chain-add').on('click', function(e
) {
444 $('#api-entity').change();