1 (function(angular
, $, _
, undefined) {
4 var schema
= CRM
.vars
.api4
.schema
;
6 var links
= CRM
.vars
.api4
.links
;
7 // Cache list of entities
9 // Cache list of actions
12 var fieldOptions
= {};
15 angular
.module('api4Explorer').config(function($routeProvider
) {
16 $routeProvider
.when('/explorer/:api4entity?/:api4action?', {
17 controller
: 'Api4Explorer',
18 templateUrl
: '~/api4Explorer/Explorer.html',
23 angular
.module('api4Explorer').controller('Api4Explorer', function($scope
, $routeParams
, $location
, $timeout
, $http
, crmUiHelp
, crmApi4
) {
24 var ts
= $scope
.ts
= CRM
.ts();
25 $scope
.entities
= entities
;
26 $scope
.actions
= actions
;
28 $scope
.fieldsAndJoins
= [];
29 $scope
.selectFieldsAndJoins
= [];
30 $scope
.availableParams
= {};
33 $scope
.resultTab
= {selected
: 'result'};
35 accessDebugOutput
: CRM
.checkPerm('access debug output')
37 var getMetaParams
= {},
38 objectParams
= {orderBy
: 'ASC', values
: '', chain
: ['Entity', '', '{}']},
39 docs
= CRM
.vars
.api4
.docs
,
42 $scope
.helpTitle
= '';
43 $scope
.helpContent
= {};
44 $scope
.entity
= $routeParams
.api4entity
;
47 $scope
.status
= 'default';
48 $scope
.loading
= false;
51 oop
: ts('PHP (oop style)'),
52 php
: ts('PHP (traditional)'),
54 cli
: ts('Command Line')
56 $scope
.code
= codeDefaults();
58 function codeDefaults() {
59 return _
.mapValues($scope
.codeLabel
, function(val
, key
) {
60 return key
=== 'oop' ? ts('Select an entity and action') : '';
64 if (!entities
.length
) {
65 formatForSelect2(schema
, entities
, 'name', ['description']);
74 function ucfirst(str
) {
75 return str
[0].toUpperCase() + str
.slice(1);
78 function lcfirst(str
) {
79 return str
[0].toLowerCase() + str
.slice(1);
82 function pluralize(str
) {
83 switch (str
[str
.length
-1]) {
87 return str
.slice(0, -1) + 'ies';
93 // Turn a flat array into a select2 array
94 function arrayToSelect2(array
) {
96 _
.each(array
, function(item
) {
97 out
.push({id
: item
, text
: item
});
102 // Reformat an existing array of objects for compatibility with select2
103 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
104 _
.each(input
, function(item
) {
105 var id
= (prefix
|| '') + item
[key
];
106 var formatted
= {id
: id
, text
: id
};
108 _
.merge(formatted
, _
.pick(item
, extra
));
110 container
.push(formatted
);
115 function getFieldList(action
) {
117 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
118 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
122 function addJoins(fieldList
, addWildcard
) {
123 var fields
= _
.cloneDeep(fieldList
),
124 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
125 _
.each(fks
.links
, function(link
) {
126 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
127 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
131 description
: 'Join to ' + link
.entity
,
132 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
139 $scope
.help = function(title
, param
) {
141 $scope
.helpTitle
= helpTitle
;
142 $scope
.helpContent
= helpContent
;
144 $scope
.helpTitle
= title
;
145 $scope
.helpContent
= param
;
149 $scope
.fieldHelp = function(fieldName
) {
150 var field
= getField(fieldName
, $scope
.entity
, $scope
.action
);
155 description
: field
.description
,
156 type
: field
.data_type
158 if (field
.default_value
) {
159 info
.default = field
.default_value
;
161 if (field
.required_if
) {
162 info
.required_if
= field
.required_if
;
163 } else if (field
.required
) {
164 info
.required
= 'true';
169 $scope
.valuesFields = function() {
170 var fields
= _
.cloneDeep($scope
.action
=== 'getFields' ? getFieldList($scope
.params
.action
|| 'get') : $scope
.fields
);
171 // Disable fields that are already in use
172 _
.each($scope
.params
.values
|| [], function(val
) {
173 (_
.findWhere(fields
, {id
: val
[0]}) || {}).disabled
= true;
175 return {results
: fields
};
178 $scope
.formatSelect2Item = function(row
) {
179 return _
.escape(row
.text
) +
180 (row
.required
? '<span class="crm-marker"> *</span>' : '') +
181 (row
.description
? '<div class="crm-select2-row-description"><p>' + _
.escape(row
.description
) + '</p></div>' : '');
184 $scope
.clearParam = function(name
) {
185 $scope
.params
[name
] = $scope
.availableParams
[name
].default;
188 $scope
.isSpecial = function(name
) {
189 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'orderBy', 'chain'];
190 return _
.contains(specialParams
, name
);
193 $scope
.selectRowCount = function() {
194 if ($scope
.isSelectRowCount()) {
195 $scope
.params
.select
= [];
197 $scope
.params
.select
= ['row_count'];
199 if ($scope
.params
.limit
== 25) {
200 $scope
.params
.limit
= 0;
205 $scope
.isSelectRowCount = function() {
206 return $scope
.params
&& $scope
.params
.select
&& $scope
.params
.select
.length
=== 1 && $scope
.params
.select
[0] === 'row_count';
209 function getEntity(entityName
) {
210 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
213 // Get all params that have been set
214 function getParams() {
216 _
.each($scope
.params
, function(param
, key
) {
217 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
218 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
219 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
225 _
.each(objectParams
, function(defaultVal
, key
) {
228 _
.each(params
[key
], function(item
) {
229 var val
= _
.cloneDeep(item
[1]);
230 // Remove blank items from "chain" array
231 if (_
.isArray(val
)) {
232 _
.eachRight(item
[1], function(v
, k
) {
239 newParam
[item
[0]] = parseYaml(val
);
241 params
[key
] = newParam
;
247 function parseYaml(input
) {
248 if (typeof input
=== 'undefined') {
254 if (_
.isObject(input
) || _
.isArray(input
)) {
255 _
.each(input
, function(item
, index
) {
256 input
[index
] = parseYaml(item
);
261 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
262 // We don't want dates parsed to js objects
263 return _
.isDate(output
) ? input
: output
;
269 function selectAction() {
270 $scope
.action
= $routeParams
.api4action
;
271 $scope
.fieldsAndJoins
.length
= 0;
272 $scope
.selectFieldsAndJoins
.length
= 0;
273 if (!actions
.length
) {
274 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
277 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
278 $scope
.fields
= getFieldList($scope
.action
);
279 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
280 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
281 $scope
.selectFieldsAndJoins
= addJoins($scope
.fields
, true);
283 $scope
.fieldsAndJoins
= $scope
.fields
;
284 $scope
.selectFieldsAndJoins
= _
.cloneDeep($scope
.fields
);
286 $scope
.selectFieldsAndJoins
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
287 _
.each(actionInfo
.params
, function (param
, name
) {
289 defaultVal
= _
.cloneDeep(param
.default);
291 switch (param
.type
[0]) {
294 format
= param
.type
[0];
305 if (name
== 'limit') {
308 if (name
=== 'values') {
309 defaultVal
= defaultValues(defaultVal
);
311 $scope
.$bindToRoute({
312 expr
: 'params["' + name
+ '"]',
316 deep
: format
=== 'json'
319 if (typeof objectParams
[name
] !== 'undefined') {
320 $scope
.$watch('params.' + name
, function(values
) {
321 // Remove empty values
322 _
.each(values
, function(clause
, index
) {
323 if (!clause
|| !clause
[0]) {
324 $scope
.params
[name
].splice(index
, 1);
328 $scope
.$watch('controls.' + name
, function(value
) {
330 $timeout(function() {
332 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
333 if (name
=== 'chain') {
334 var num
= $scope
.params
.chain
.length
;
335 defaultOp
[0] = field
;
336 field
= 'name_me_' + num
;
338 $scope
.params
[name
].push([field
, defaultOp
]);
339 $scope
.controls
[name
] = null;
345 $scope
.availableParams
= actionInfo
.params
;
350 function defaultValues(defaultVal
) {
351 _
.each($scope
.fields
, function(field
) {
352 if (field
.required
) {
353 defaultVal
.push([field
.id
, '']);
359 function stringify(value
, trim
) {
360 if (typeof value
=== 'undefined') {
363 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
365 str
= str
.slice(1, -1);
370 function writeCode() {
371 var code
= codeDefaults(),
372 entity
= $scope
.entity
,
373 action
= $scope
.action
,
374 params
= getParams(),
375 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
377 if ($scope
.entity
&& $scope
.action
) {
378 if (action
.slice(0, 3) === 'get') {
379 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
380 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
382 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
383 paramCount
= _
.size(params
),
384 isSelectRowCount
= params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count',
387 if (isSelectRowCount
) {
388 results
= result
+ 'Count';
392 code
.js
= "CRM.api4('" + entity
+ "', '" + action
+ "', {";
393 _
.each(params
, function(param
, key
) {
394 code
.js
+= "\n " + key
+ ': ' + stringify(param
) +
395 (++i
< paramCount
? ',' : '');
396 if (key
=== 'checkPermissions') {
397 code
.js
+= ' // IGNORED: permissions are always enforced from client-side requests';
401 if (index
|| index
=== 0) {
402 code
.js
+= ', ' + JSON
.stringify(index
);
404 code
.js
+= ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
407 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
408 _
.each(params
, function(param
, key
) {
409 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
412 if (index
|| index
=== 0) {
413 code
.php
+= ', ' + phpFormat(index
);
418 if (entity
.substr(0, 7) !== 'Custom_') {
419 code
.oop
= '$' + results
+ " = \\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
421 code
.oop
= '$' + results
+ " = \\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
423 _
.each(params
, function(param
, key
) {
425 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
426 _
.each(param
, function(item
, index
) {
427 val
= phpFormat(index
) + ', ' + phpFormat(item
, 4);
428 code
.oop
+= "\n ->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
430 } else if (key
=== 'where') {
431 _
.each(param
, function (clause
) {
432 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
433 code
.oop
+= "\n ->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
435 code
.oop
+= "\n ->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
438 } else if (key
=== 'select' && isSelectRowCount
) {
439 code
.oop
+= "\n ->selectRowCount()";
441 code
.oop
+= "\n ->set" + ucfirst(key
) + '(' + phpFormat(param
, 4) + ')';
444 code
.oop
+= "\n ->execute()";
445 if (isSelectRowCount
) {
446 code
.oop
+= "\n ->count()";
447 } else if (_
.isNumber(index
)) {
448 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
450 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
451 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
453 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
454 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
458 if (!_
.isNumber(index
) && !isSelectRowCount
) {
459 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
463 code
.cli
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
465 _
.each(code
, function(val
, type
) {
466 $scope
.code
[type
] = prettyPrintOne(_
.escape(val
));
470 function isInt(value
) {
471 if (_
.isFinite(value
)) {
474 if (!_
.isString(value
)) {
477 return /^-{0,1}\d+$/.test(value
);
480 function formatMeta(resp
) {
482 _
.each(resp
, function(val
, key
) {
483 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
484 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
487 return prettyPrintOne(_
.escape(ret
));
490 $scope
.execute = function() {
491 $scope
.status
= 'warning';
492 $scope
.loading
= true;
493 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
494 params
: angular
.toJson(getParams()),
495 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
498 'X-Requested-With': 'XMLHttpRequest'
500 }).then(function(resp
) {
501 $scope
.loading
= false;
502 $scope
.status
= 'success';
503 $scope
.debug
= debugFormat(resp
.data
);
504 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
506 $scope
.loading
= false;
507 $scope
.status
= 'danger';
508 $scope
.debug
= debugFormat(resp
.data
);
509 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
513 function debugFormat(data
) {
514 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
520 * Format value to look like php code
522 function phpFormat(val
, indent
) {
523 if (typeof val
=== 'undefined') {
526 if (val
=== null || val
=== true || val
=== false) {
527 return JSON
.stringify(val
).toUpperCase();
529 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
531 baseLine
= indent
? indent
.slice(0, -2) : '',
532 newLine
= indent
? '\n' : '',
533 trailingComma
= indent
? ',' : '';
534 if ($.isPlainObject(val
)) {
535 $.each(val
, function(k
, v
) {
536 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
538 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
540 if ($.isArray(val
)) {
541 $.each(val
, function(k
, v
) {
542 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
544 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
546 if (_
.isString(val
) && !_
.contains(val
, "'")) {
547 return "'" + val
+ "'";
549 return JSON
.stringify(val
).replace(/\$/g, '\\$');
552 function fetchMeta() {
553 crmApi4(getMetaParams
)
554 .then(function(data
) {
556 getEntity().actions
= data
.actions
;
562 // Help for an entity with no action selected
563 function showEntityHelp(entityName
) {
564 var entityInfo
= getEntity(entityName
);
565 $scope
.helpTitle
= helpTitle
= $scope
.entity
;
566 $scope
.helpContent
= helpContent
= {
567 description
: entityInfo
.description
,
568 comment
: entityInfo
.comment
572 if (!$scope
.entity
) {
573 $scope
.helpTitle
= helpTitle
= ts('APIv4 Explorer');
574 $scope
.helpContent
= helpContent
= {description
: docs
.description
, comment
: docs
.comment
};
575 } else if (!actions
.length
&& !getEntity().actions
) {
576 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
583 showEntityHelp($scope
.entity
);
586 // Update route when changing entity
587 $scope
.$watch('entity', function(newVal
, oldVal
) {
588 if (oldVal
!== newVal
) {
589 // Flush actions cache to re-fetch for new entity
591 $location
.url('/explorer/' + newVal
);
595 // Update route when changing actions
596 $scope
.$watch('action', function(newVal
, oldVal
) {
597 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
598 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
600 $scope
.helpTitle
= helpTitle
= $scope
.entity
+ '::' + newVal
;
601 $scope
.helpContent
= helpContent
= _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment']);
605 $scope
.paramDoc = function(name
) {
606 return docs
.params
[name
];
609 $scope
.$watch('params', writeCode
, true);
610 $scope
.$watch('index', writeCode
);
615 angular
.module('api4Explorer').directive('crmApi4WhereClause', function($timeout
) {
618 data
: '=crmApi4WhereClause'
620 templateUrl
: '~/api4Explorer/WhereClause.html',
621 link: function (scope
, element
, attrs
) {
622 var ts
= scope
.ts
= CRM
.ts();
623 scope
.newClause
= '';
624 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
625 scope
.operators
= CRM
.vars
.api4
.operators
;
627 scope
.addGroup = function(op
) {
628 scope
.data
.where
.push([op
, []]);
631 scope
.removeGroup = function() {
632 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
635 scope
.onSort = function(event
, ui
) {
636 $('.api4-where-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
637 $('.api4-input.form-inline').css('margin-left', '');
640 // Indent clause while dragging between nested groups
641 scope
.onSortOver = function(event
, ui
) {
644 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
646 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
649 scope
.$watch('newClause', function(value
) {
651 $timeout(function() {
653 scope
.data
.where
.push([field
, '=', '']);
654 scope
.newClause
= null;
658 scope
.$watch('data.where', function(values
) {
659 // Remove empty values
660 _
.each(values
, function(clause
, index
) {
661 if (typeof clause
!== 'undefined' && !clause
[0]) {
662 values
.splice(index
, 1);
664 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
666 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
675 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
678 data
: '=api4ExpValue'
681 link: function (scope
, element
, attrs
, ctrl
) {
682 var ts
= scope
.ts
= CRM
.ts(),
683 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
684 entity
= $routeParams
.api4entity
,
685 action
= scope
.data
.action
|| $routeParams
.api4action
;
687 function destroyWidget() {
688 var $el
= $(element
);
689 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
690 $el
.crmDatepicker('destroy');
692 if ($el
.is('.select2-container + input')) {
693 $el
.crmEntityRef('destroy');
695 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
698 function makeWidget(field
, op
) {
699 var $el
= $(element
),
700 inputType
= field
.input_type
,
701 dataType
= field
.data_type
;
703 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
705 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
706 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
710 if (inputType
=== 'Date') {
711 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
712 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
714 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
715 if (field
.fk_entity
) {
716 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
717 } else if (field
.options
) {
718 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
719 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
721 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
722 options
.push({id
: key
, text
: val
});
724 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
726 } else if (dataType
=== 'Boolean') {
727 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
728 {id
: 'true', text
: ts('Yes')},
729 {id
: 'false', text
: ts('No')}
732 } else if (dataType
=== 'Integer' && !multi
) {
733 $el
.attr('type', 'number');
737 function loadFieldOptions(entity
) {
738 if (!fieldOptions
[entity
+ action
]) {
739 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
742 where
: [["options", "!=", false]],
743 select
: ["name", "options"]
746 return fieldOptions
[entity
+ action
];
749 // Copied from ng-list but applied conditionally if field is multi-valued
750 var parseList = function(viewValue
) {
751 // If the viewValue is invalid (say required but empty) it will be `undefined`
752 if (_
.isUndefined(viewValue
)) return;
761 _
.each(viewValue
.split(','), function(value
) {
762 if (value
) list
.push(_
.trim(value
));
769 // Copied from ng-list
770 ctrl
.$parsers
.push(parseList
);
771 ctrl
.$formatters
.push(function(value
) {
772 return _
.isArray(value
) ? value
.join(', ') : value
;
775 // Copied from ng-list
776 ctrl
.$isEmpty = function(value
) {
777 return !value
|| !value
.length
;
780 scope
.$watchCollection('data', function(data
) {
782 var field
= getField(data
.field
, entity
, action
);
784 makeWidget(field
, data
.op
);
792 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
795 chain
: '=api4ExpChain',
799 templateUrl
: '~/api4Explorer/Chain.html',
800 link: function (scope
, element
, attrs
) {
801 var ts
= scope
.ts
= CRM
.ts();
803 function changeEntity(newEntity
, oldEntity
) {
804 // When clearing entity remove this chain
809 // Reset action && index
810 if (newEntity
!== oldEntity
) {
811 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
813 if (getEntity(newEntity
).actions
) {
816 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
817 .then(function(data
) {
818 getEntity(data
.entity
).actions
= data
;
819 if (data
.entity
=== scope
.chain
[1][0]) {
826 function setActions() {
827 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
830 // Set default params when choosing action
831 function changeAction(newAction
, oldAction
) {
834 if (newAction
&& newAction
!== oldAction
) {
836 scope
.chain
[1][3] = '';
837 // Look for links back to main entity
838 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
839 if (field
.fk_entity
=== scope
.mainEntity
) {
840 link
= [field
.name
, '$id'];
843 // Look for links from main entity
844 if (!link
&& newAction
!== 'create') {
845 _
.each(entityFields(scope
.mainEntity
), function(field
) {
846 if (field
.fk_entity
=== scope
.chain
[1][0]) {
847 link
= ['id', '$' + field
.name
];
848 // Since we're specifying the id, set index to getsingle
849 scope
.chain
[1][3] = '0';
853 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
854 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
856 else if (link
&& _
.contains(['create'], newAction
)) {
857 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
859 else if (link
&& _
.contains(['save'], newAction
)) {
860 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
862 scope
.chain
[1][2] = '{}';
867 scope
.$watch("chain[1][0]", changeEntity
);
868 scope
.$watch("chain[1][1]", changeAction
);
873 function getEntity(entityName
) {
874 return _
.findWhere(schema
, {name
: entityName
});
877 function entityFields(entityName
, action
) {
878 var entity
= getEntity(entityName
);
879 if (entity
&& action
&& entity
.actions
) {
880 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
882 return _
.result(entity
, 'fields');
885 function getField(fieldName
, entity
, action
) {
886 var fieldNames
= fieldName
.split('.');
887 return get(entity
, fieldNames
);
889 function get(entity
, fieldNames
) {
890 if (fieldNames
.length
=== 1) {
891 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
893 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
897 var linkName
= fieldNames
.shift(),
898 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
899 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
900 return get(newEntity
, fieldNames
);
904 // Collapsible optgroups for select2
907 .on('select2-open', function(e
) {
908 if ($(e
.target
).hasClass('collapsible-optgroups')) {
910 .off('.collapseOptionGroup')
911 .addClass('collapsible-optgroups-enabled')
912 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
913 $(this).parent().toggleClass('optgroup-expanded');
917 .on('select2-close', function() {
918 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
921 })(angular
, CRM
.$, CRM
._
);