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 console
.log($(returnTpl({})));
122 $('#api-return-value').crmSelect2({data
: fields
, multiple
: true});
126 * Fetch actions for entity
128 function getActions() {
130 CRM
.api3(entity
, 'getactions').done(function(data
) {
131 // Ensure 'get' is always an action
132 actions
= _
.union(['get'], data
.values
);
142 * Called after getActions to populate action list
145 function populateActions(el
) {
146 $('#api-action').select2({
147 data
: _
.transform(actions
, function(ret
, item
) {ret
.push({text
: item
, id
: item
})})
152 * Called after getfields to show buttons and required fields
155 function showFields(required
) {
156 $('#api-params').empty();
157 $('#api-param-buttons').show();
158 if (required
.length
) {
159 _
.each(required
, addField
);
166 * Add/remove option list for selected field's pseudoconstant
168 function toggleOptions() {
169 var name
= $(this).val(),
170 $valField
= $(this).closest('tr').find('.api-param-value');
172 $valField
.val('').select2({
174 data
: _
.transform(options
[name
], function(result
, option
) {
175 result
.push({id
: option
.key
, text
: option
.value
});
179 else if ($valField
.data('select2')) {
180 $valField
.select2('destroy');
185 * Attempt to parse a string into a value of the intended type
188 function evaluate(val
, makeArray
) {
193 var first
= val
.charAt(0),
194 last
= val
.slice(-1);
196 if (val
=== 'true' || val
=== 'false' || val
=== 'null' || !isNaN(val
)) {
200 if ((first
=== '"' || first
=== "'") && last
=== first
) {
201 return val
.slice(1, -1);
204 if ((first
=== '[' && last
=== ']') || (first
=== '{' && last
=== '}')) {
205 return eval('(' + val
+ ')');
207 // Transform csv to array
208 if (makeArray
&& val
.indexOf(',') > 0) {
209 return val
.split(',');
211 // Ok ok it's really a string
214 // If eval crashed return undefined
220 * Format value to look like php code
223 function phpFormat(val
) {
225 if ($.isPlainObject(val
)) {
226 $.each(val
, function(k
, v
) {
227 ret
+= (ret
? ', ' : '') + "'" + k
+ "' => " + phpFormat(v
);
229 return 'array(' + ret
+ ')';
231 if ($.isArray(val
)) {
232 $.each(val
, function(k
, v
) {
233 ret
+= (ret
? ', ' : '') + phpFormat(v
);
235 return 'array(' + ret
+ ')';
237 return JSON
.stringify(val
);
241 * Smarty doesn't support array literals so we provide a stub
244 function smartyFormat(js
, key
) {
245 if (js
.indexOf('[') > -1 || js
.indexOf('{') > -1) {
247 return '$' + key
.replace(/[. -]/g, '_');
253 * Create the params array from user input
256 function buildParams(e
) {
258 $('.api-param-checkbox:checked').each(function() {
259 params
[this.name
] = 1;
261 $('input.api-param-value, input.api-option-value').each(function() {
262 var $row
= $(this).closest('tr'),
263 val
= evaluate($(this).val(), $(this).is('.select2-offscreen')),
264 name
= $('input.api-param-name', $row
).val(),
265 op
= $('select.api-param-op', $row
).val() || '=';
267 // Ignore blank values for the return field
268 if ($(this).is('#api-return-value') && !val
) {
271 // Special syntax for api chaining
272 if (!name
&& $('select.api-chain-entity', $row
).val()) {
273 name
= 'api.' + $('select.api-chain-entity', $row
).val() + '.' + $('select.api-chain-action', $row
).val();
275 // Special handling for options
276 if ($(this).is('.api-option-value')) {
277 op
= $('input.api-option-name', $row
).val();
282 if (name
&& val
!== undefined) {
283 params
[name
] = op
=== '=' ? val
: (params
[name
] || {});
285 params
[name
][op
] = val
;
289 else if (name
&& (!e
|| e
.type
!== 'keyup')) {
293 if (entity
&& action
) {
298 function setError(el
) {
299 if (!$(el
).hasClass('crm-error')) {
301 .addClass('crm-error')
303 .attr('title', ts('Syntax error'))
304 .before('<div class="icon red-icon ui-icon-alert"/>');
308 function clearError(el
) {
310 .removeClass('crm-error')
313 .siblings('.ui-icon-alert').remove();
316 function formatQuery() {
318 smarty
: "{crmAPI var='result' entity='" + entity
+ "' action='" + action
+ "'",
319 php
: "$result = civicrm_api3('" + entity
+ "', '" + action
+ "'",
320 json
: "CRM.api3('" + entity
+ "', '" + action
+ "'",
321 rest
: CRM
.config
.resourceBase
+ "extern/rest.php?entity=" + entity
+ "&action=" + action
+ "&json=" + JSON
.stringify(params
) + "&api_key=yoursitekey&key=yourkey"
324 $.each(params
, function(key
, value
) {
325 var js
= JSON
.stringify(value
);
327 q
.php
+= ", array(\n";
332 q
.php
+= " '" + key
+ "' => " + phpFormat(value
) + ",\n";
333 q
.json
+= " \"" + key
+ '": ' + js
;
334 q
.smarty
+= ' ' + key
+ '=' + smartyFormat(js
, key
);
341 q
.json
+= ").done(function(result) {\n // do something\n});";
342 q
.smarty
+= "}\n{foreach from=$result.values item=" + entity
.toLowerCase() + "}\n {$" + entity
.toLowerCase() + ".some_field}\n{/foreach}";
343 if (action
.indexOf('get') < 0) {
344 q
.smarty
= '{* Smarty API only works with get actions *}';
345 } else if (smartyStub
) {
346 q
.smarty
= "{* Smarty does not have a syntax for array literals; assign complex variables on the server *}\n" + q
.smarty
;
348 $.each(q
, function(type
, val
) {
349 $('#api-' + type
).removeClass('prettyprinted').text(val
);
356 if (!entity
|| !action
) {
357 alert(ts('Select an entity.'));
360 if (action
.indexOf('get') < 0) {
361 var msg
= action
=== 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
362 CRM
.confirm({title
: ts('Confirm %1', {1: action
}), message
: msg
}).on('crmConfirm:yes', execute
);
369 $('#api-result').html('<div class="crm-loading-element"></div>');
371 url
: CRM
.url('civicrm/ajax/rest'),
376 json
: JSON
.stringify(params
)
378 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
380 }).done(function(text
) {
381 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text
);
386 $(document
).ready(function() {
387 $('form#api-explorer')
388 .on('change', '#api-entity, #api-action', function() {
389 entity
= $('#api-entity').val();
390 if ($(this).is('#api-entity')) {
391 $('#api-action').select2('val', 'get');
394 action
= $('#api-action').val();
395 if (entity
&& action
) {
396 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
397 $('#api-params-table thead').show();
401 $('#api-params, #api-generated pre').empty();
402 $('#api-param-buttons, #api-params-table thead').hide();
405 .on('change keyup', 'input.api-input, #api-params select', buildParams
)
406 .on('submit', submit
);
408 .on('change', '.api-param-name', toggleOptions
)
409 .on('change', '.api-param-name, .api-option-name', function() {
410 if ($(this).val() === '-') {
411 $(this).select2('destroy');
412 $(this).val('').focus();
415 .on('click', '.api-param-remove', function(e
) {
417 $(this).closest('tr').remove();
420 $('#api-params-add').on('click', function(e
) {
424 $('#api-option-add').on('click', function(e
) {
428 $('#api-chain-add').on('click', function(e
) {
432 $('#api-entity').change();