0a4f89e198bf79210efa9d6663385c32017a34a5
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 // Ensure 'get' is always an action
131 actions
= _
.union(['get'], data
.values
);
141 * Called after getActions to populate action list
144 function populateActions(el
) {
145 $('#api-action').select2({
146 data
: _
.transform(actions
, function(ret
, item
) {ret
.push({text
: item
, id
: item
})})
151 * Called after getfields to show buttons and required fields
154 function showFields(required
) {
155 $('#api-params').empty();
156 $('#api-param-buttons').show();
157 if (required
.length
) {
158 _
.each(required
, addField
);
165 * Add/remove option list for selected field's pseudoconstant
167 function toggleOptions() {
168 var name
= $(this).val(),
169 $valField
= $(this).closest('tr').find('.api-param-value');
171 $valField
.val('').select2({
173 data
: _
.transform(options
[name
], function(result
, option
) {
174 result
.push({id
: option
.key
, text
: option
.value
});
178 else if ($valField
.data('select2')) {
179 $valField
.select2('destroy');
184 * Attempt to parse a string into a value of the intended type
186 * @param makeArray bool
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
;
287 if ($(this).hasClass('crm-error')) {
291 else if (name
&& (!e
|| e
.type
!== 'keyup')) {
295 if (entity
&& action
) {
300 function setError(el
) {
301 if (!$(el
).hasClass('crm-error')) {
302 var msg
= ts('Syntax error: input should be valid JSON or a quoted string.');
304 .addClass('crm-error')
307 .before('<div class="icon red-icon ui-icon-alert" title="'+msg
+'"/>')
312 function clearError(el
) {
314 .removeClass('crm-error')
318 .siblings('.ui-icon-alert').remove();
321 function formatQuery() {
323 smarty
: "{crmAPI var='result' entity='" + entity
+ "' action='" + action
+ "'",
324 php
: "$result = civicrm_api3('" + entity
+ "', '" + action
+ "'",
325 json
: "CRM.api3('" + entity
+ "', '" + action
+ "'",
326 rest
: CRM
.config
.resourceBase
+ "extern/rest.php?entity=" + entity
+ "&action=" + action
+ "&json=" + JSON
.stringify(params
) + "&api_key=yoursitekey&key=yourkey"
329 $.each(params
, function(key
, value
) {
330 var js
= JSON
.stringify(value
);
332 q
.php
+= ", array(\n";
337 q
.php
+= " '" + key
+ "' => " + phpFormat(value
) + ",\n";
338 q
.json
+= " \"" + key
+ '": ' + js
;
339 q
.smarty
+= ' ' + key
+ '=' + smartyFormat(js
, key
);
346 q
.json
+= ").done(function(result) {\n // do something\n});";
347 q
.smarty
+= "}\n{foreach from=$result.values item=" + entity
.toLowerCase() + "}\n {$" + entity
.toLowerCase() + ".some_field}\n{/foreach}";
348 if (action
.indexOf('get') < 0) {
349 q
.smarty
= '{* Smarty API only works with get actions *}';
350 } else if (smartyStub
) {
351 q
.smarty
= "{* Smarty does not have a syntax for array literals; assign complex variables on the server *}\n" + q
.smarty
;
353 $.each(q
, function(type
, val
) {
354 $('#api-' + type
).removeClass('prettyprinted').text(val
);
361 if (!entity
|| !action
) {
362 alert(ts('Select an entity.'));
365 if (action
.indexOf('get') < 0) {
366 var msg
= action
=== 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
367 CRM
.confirm({title
: ts('Confirm %1', {1: action
}), message
: msg
}).on('crmConfirm:yes', execute
);
374 $('#api-result').html('<div class="crm-loading-element"></div>');
376 url
: CRM
.url('civicrm/ajax/rest'),
381 json
: JSON
.stringify(params
)
383 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
385 }).done(function(text
) {
386 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text
);
391 $(document
).ready(function() {
392 $('form#api-explorer')
393 .on('change', '#api-entity, #api-action', function() {
394 entity
= $('#api-entity').val();
395 if ($(this).is('#api-entity')) {
396 $('#api-action').select2('val', 'get');
399 action
= $('#api-action').val();
400 if (entity
&& action
) {
401 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
402 $('#api-params-table thead').show();
406 $('#api-params, #api-generated pre').empty();
407 $('#api-param-buttons, #api-params-table thead').hide();
410 .on('change keyup', 'input.api-input, #api-params select', buildParams
)
411 .on('submit', submit
);
413 .on('change', '.api-param-name', toggleOptions
)
414 .on('change', '.api-param-name, .api-option-name', function() {
415 if ($(this).val() === '-') {
416 $(this).select2('destroy');
417 $(this).val('').focus();
420 .on('click', '.api-param-remove', function(e
) {
422 $(this).closest('tr').remove();
425 $('#api-params-add').on('click', function(e
) {
429 $('#api-option-add').on('click', function(e
) {
433 $('#api-chain-add').on('click', function(e
) {
437 $('#api-entity').change();