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
.availableParams
= {};
32 var getMetaParams
= {},
33 objectParams
= {orderBy
: 'ASC', values
: '', chain
: ['Entity', '', '{}']},
34 docs
= CRM
.vars
.api4
.docs
,
37 $scope
.helpTitle
= '';
38 $scope
.helpContent
= {};
39 $scope
.entity
= $routeParams
.api4entity
;
41 $scope
.status
= 'default';
42 $scope
.loading
= false;
45 oop
: ts('PHP (oop style)'),
46 php
: ts('PHP (traditional)'),
48 cli
: ts('Command Line')
50 $scope
.code
= codeDefaults();
52 function codeDefaults() {
53 return _
.mapValues($scope
.codeLabel
, function(val
, key
) {
54 return key
=== 'oop' ? ts('Select an entity and action') : '';
58 if (!entities
.length
) {
59 formatForSelect2(schema
, entities
, 'name', ['description']);
68 function ucfirst(str
) {
69 return str
[0].toUpperCase() + str
.slice(1);
72 function lcfirst(str
) {
73 return str
[0].toLowerCase() + str
.slice(1);
76 function pluralize(str
) {
77 switch (str
[str
.length
-1]) {
81 return str
.slice(0, -1) + 'ies';
87 // Turn a flat array into a select2 array
88 function arrayToSelect2(array
) {
90 _
.each(array
, function(item
) {
91 out
.push({id
: item
, text
: item
});
96 // Reformat an existing array of objects for compatibility with select2
97 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
98 _
.each(input
, function(item
) {
99 var id
= (prefix
|| '') + item
[key
];
100 var formatted
= {id
: id
, text
: id
};
102 _
.merge(formatted
, _
.pick(item
, extra
));
104 container
.push(formatted
);
109 function getFieldList(action
) {
111 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
112 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
116 function addJoins(fieldList
) {
117 var fields
= _
.cloneDeep(fieldList
),
118 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
119 _
.each(fks
.links
, function(link
) {
120 var linkFields
= entityFields(link
.entity
);
124 description
: 'Join to ' + link
.entity
,
125 children
: formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.')
132 $scope
.help = function(title
, param
) {
134 $scope
.helpTitle
= helpTitle
;
135 $scope
.helpContent
= helpContent
;
137 $scope
.helpTitle
= title
;
138 $scope
.helpContent
= param
;
142 $scope
.fieldHelp = function(fieldName
) {
143 var field
= getField(fieldName
, $scope
.entity
, $scope
.action
);
148 description
: field
.description
,
149 type
: field
.data_type
151 if (field
.default_value
) {
152 info
.default = field
.default_value
;
154 if (field
.required_if
) {
155 info
.required_if
= field
.required_if
;
156 } else if (field
.required
) {
157 info
.required
= 'true';
162 $scope
.valuesFields = function() {
163 var fields
= _
.cloneDeep($scope
.action
=== 'getFields' ? getFieldList($scope
.params
.action
|| 'get') : $scope
.fields
);
164 // Disable fields that are already in use
165 _
.each($scope
.params
.values
|| [], function(val
) {
166 (_
.findWhere(fields
, {id
: val
[0]}) || {}).disabled
= true;
168 return {results
: fields
};
171 $scope
.formatSelect2Item = function(row
) {
172 return _
.escape(row
.text
) +
173 (row
.required
? '<span class="crm-marker"> *</span>' : '') +
174 (row
.description
? '<div class="crm-select2-row-description"><p>' + _
.escape(row
.description
) + '</p></div>' : '');
177 $scope
.clearParam = function(name
) {
178 $scope
.params
[name
] = $scope
.availableParams
[name
].default;
181 $scope
.isSpecial = function(name
) {
182 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'orderBy', 'chain'];
183 return _
.contains(specialParams
, name
);
186 $scope
.selectRowCount = function() {
187 if ($scope
.isSelectRowCount()) {
188 $scope
.params
.select
= [];
190 $scope
.params
.select
= ['row_count'];
192 if ($scope
.params
.limit
== 25) {
193 $scope
.params
.limit
= 0;
198 $scope
.isSelectRowCount = function() {
199 return $scope
.params
&& $scope
.params
.select
&& $scope
.params
.select
.length
=== 1 && $scope
.params
.select
[0] === 'row_count';
202 function getEntity(entityName
) {
203 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
206 // Get all params that have been set
207 function getParams() {
209 _
.each($scope
.params
, function(param
, key
) {
210 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
211 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
212 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
218 _
.each(objectParams
, function(defaultVal
, key
) {
221 _
.each(params
[key
], function(item
) {
222 var val
= _
.cloneDeep(item
[1]);
223 // Remove blank items from "chain" array
224 if (_
.isArray(val
)) {
225 _
.eachRight(item
[1], function(v
, k
) {
232 newParam
[item
[0]] = parseYaml(val
);
234 params
[key
] = newParam
;
240 function parseYaml(input
) {
241 if (typeof input
=== 'undefined') {
247 if (_
.isObject(input
) || _
.isArray(input
)) {
248 _
.each(input
, function(item
, index
) {
249 input
[index
] = parseYaml(item
);
254 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
255 // We don't want dates parsed to js objects
256 return _
.isDate(output
) ? input
: output
;
262 function selectAction() {
263 $scope
.action
= $routeParams
.api4action
;
264 $scope
.fieldsAndJoins
= [];
265 if (!actions
.length
) {
266 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
269 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
270 $scope
.fields
= getFieldList($scope
.action
);
271 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
272 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
274 $scope
.fieldsAndJoins
= $scope
.fields
;
276 _
.each(actionInfo
.params
, function (param
, name
) {
278 defaultVal
= _
.cloneDeep(param
.default);
280 switch (param
.type
[0]) {
283 format
= param
.type
[0];
294 if (name
== 'limit') {
297 if (name
=== 'values') {
298 defaultVal
= defaultValues(defaultVal
);
300 $scope
.$bindToRoute({
301 expr
: 'params["' + name
+ '"]',
305 deep
: format
=== 'json'
308 if (typeof objectParams
[name
] !== 'undefined') {
309 $scope
.$watch('params.' + name
, function(values
) {
310 // Remove empty values
311 _
.each(values
, function(clause
, index
) {
312 if (!clause
|| !clause
[0]) {
313 $scope
.params
[name
].splice(index
, 1);
317 $scope
.$watch('controls.' + name
, function(value
) {
319 $timeout(function() {
321 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
322 if (name
=== 'chain') {
323 var num
= $scope
.params
.chain
.length
;
324 defaultOp
[0] = field
;
325 field
= 'name_me_' + num
;
327 $scope
.params
[name
].push([field
, defaultOp
]);
328 $scope
.controls
[name
] = null;
334 $scope
.availableParams
= actionInfo
.params
;
339 function defaultValues(defaultVal
) {
340 _
.each($scope
.fields
, function(field
) {
341 if (field
.required
) {
342 defaultVal
.push([field
.id
, '']);
348 function stringify(value
, trim
) {
349 if (typeof value
=== 'undefined') {
352 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
354 str
= str
.slice(1, -1);
359 function writeCode() {
360 var code
= codeDefaults(),
361 entity
= $scope
.entity
,
362 action
= $scope
.action
,
363 params
= getParams(),
364 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
366 if ($scope
.entity
&& $scope
.action
) {
367 if (action
.slice(0, 3) === 'get') {
368 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
369 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
371 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
372 paramCount
= _
.size(params
),
373 isSelectRowCount
= params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count',
376 if (isSelectRowCount
) {
377 results
= result
+ 'Count';
381 code
.js
= "CRM.api4('" + entity
+ "', '" + action
+ "', {";
382 _
.each(params
, function(param
, key
) {
383 code
.js
+= "\n " + key
+ ': ' + stringify(param
) +
384 (++i
< paramCount
? ',' : '');
385 if (key
=== 'checkPermissions') {
386 code
.js
+= ' // IGNORED: permissions are always enforced from client-side requests';
390 if (index
|| index
=== 0) {
391 code
.js
+= ', ' + JSON
.stringify(index
);
393 code
.js
+= ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
396 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
397 _
.each(params
, function(param
, key
) {
398 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
401 if (index
|| index
=== 0) {
402 code
.php
+= ', ' + phpFormat(index
);
407 if (entity
.substr(0, 7) !== 'Custom_') {
408 code
.oop
= '$' + results
+ " = \\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
410 code
.oop
= '$' + results
+ " = \\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
412 _
.each(params
, function(param
, key
) {
414 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
415 _
.each(param
, function(item
, index
) {
416 val
= phpFormat(index
) + ', ' + phpFormat(item
, 4);
417 code
.oop
+= "\n ->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
419 } else if (key
=== 'where') {
420 _
.each(param
, function (clause
) {
421 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
422 code
.oop
+= "\n ->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
424 code
.oop
+= "\n ->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
427 } else if (key
=== 'select' && isSelectRowCount
) {
428 code
.oop
+= "\n ->selectRowCount()";
430 code
.oop
+= "\n ->set" + ucfirst(key
) + '(' + phpFormat(param
, 4) + ')';
433 code
.oop
+= "\n ->execute()";
434 if (isSelectRowCount
) {
435 code
.oop
+= "\n ->count()";
436 } else if (_
.isNumber(index
)) {
437 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
439 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
440 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
442 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
443 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
447 if (!_
.isNumber(index
) && !isSelectRowCount
) {
448 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
452 code
.cli
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
454 _
.each(code
, function(val
, type
) {
455 $scope
.code
[type
] = prettyPrintOne(_
.escape(val
));
459 function isInt(value
) {
460 if (_
.isFinite(value
)) {
463 if (!_
.isString(value
)) {
466 return /^-{0,1}\d+$/.test(value
);
469 function formatMeta(resp
) {
471 _
.each(resp
, function(val
, key
) {
472 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
473 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
476 return prettyPrintOne(_
.escape(ret
));
479 $scope
.execute = function() {
480 $scope
.status
= 'warning';
481 $scope
.loading
= true;
482 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
483 params
: angular
.toJson(getParams()),
484 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
487 'X-Requested-With': 'XMLHttpRequest'
489 }).then(function(resp
) {
490 $scope
.loading
= false;
491 $scope
.status
= 'success';
492 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
494 $scope
.loading
= false;
495 $scope
.status
= 'danger';
496 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
501 * Format value to look like php code
503 function phpFormat(val
, indent
) {
504 if (typeof val
=== 'undefined') {
507 if (val
=== null || val
=== true || val
=== false) {
508 return JSON
.stringify(val
).toUpperCase();
510 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
512 baseLine
= indent
? indent
.slice(0, -2) : '',
513 newLine
= indent
? '\n' : '',
514 trailingComma
= indent
? ',' : '';
515 if ($.isPlainObject(val
)) {
516 $.each(val
, function(k
, v
) {
517 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
519 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
521 if ($.isArray(val
)) {
522 $.each(val
, function(k
, v
) {
523 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
525 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
527 if (_
.isString(val
) && !_
.contains(val
, "'")) {
528 return "'" + val
+ "'";
530 return JSON
.stringify(val
).replace(/\$/g, '\\$');
533 function fetchMeta() {
534 crmApi4(getMetaParams
)
535 .then(function(data
) {
537 getEntity().actions
= data
.actions
;
543 // Help for an entity with no action selected
544 function showEntityHelp(entityName
) {
545 var entityInfo
= getEntity(entityName
);
546 $scope
.helpTitle
= helpTitle
= $scope
.entity
;
547 $scope
.helpContent
= helpContent
= {
548 description
: entityInfo
.description
,
549 comment
: entityInfo
.comment
553 if (!$scope
.entity
) {
554 $scope
.helpTitle
= helpTitle
= ts('APIv4 Explorer');
555 $scope
.helpContent
= helpContent
= {description
: docs
.description
, comment
: docs
.comment
};
556 } else if (!actions
.length
&& !getEntity().actions
) {
557 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
564 showEntityHelp($scope
.entity
);
567 // Update route when changing entity
568 $scope
.$watch('entity', function(newVal
, oldVal
) {
569 if (oldVal
!== newVal
) {
570 // Flush actions cache to re-fetch for new entity
572 $location
.url('/explorer/' + newVal
);
576 // Update route when changing actions
577 $scope
.$watch('action', function(newVal
, oldVal
) {
578 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
579 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
581 $scope
.helpTitle
= helpTitle
= $scope
.entity
+ '::' + newVal
;
582 $scope
.helpContent
= helpContent
= _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment']);
586 $scope
.paramDoc = function(name
) {
587 return docs
.params
[name
];
590 $scope
.$watch('params', writeCode
, true);
591 $scope
.$watch('index', writeCode
);
596 angular
.module('api4Explorer').directive('crmApi4WhereClause', function($timeout
) {
599 data
: '=crmApi4WhereClause'
601 templateUrl
: '~/api4Explorer/WhereClause.html',
602 link: function (scope
, element
, attrs
) {
603 var ts
= scope
.ts
= CRM
.ts();
604 scope
.newClause
= '';
605 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
606 scope
.operators
= CRM
.vars
.api4
.operators
;
608 scope
.addGroup = function(op
) {
609 scope
.data
.where
.push([op
, []]);
612 scope
.removeGroup = function() {
613 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
616 scope
.onSort = function(event
, ui
) {
617 $('.api4-where-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
618 $('.api4-input.form-inline').css('margin-left', '');
621 // Indent clause while dragging between nested groups
622 scope
.onSortOver = function(event
, ui
) {
625 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
627 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
630 scope
.$watch('newClause', function(value
) {
632 $timeout(function() {
634 scope
.data
.where
.push([field
, '=', '']);
635 scope
.newClause
= null;
639 scope
.$watch('data.where', function(values
) {
640 // Remove empty values
641 _
.each(values
, function(clause
, index
) {
642 if (typeof clause
!== 'undefined' && !clause
[0]) {
643 values
.splice(index
, 1);
645 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
647 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
656 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
659 data
: '=api4ExpValue'
662 link: function (scope
, element
, attrs
, ctrl
) {
663 var ts
= scope
.ts
= CRM
.ts(),
664 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
665 entity
= $routeParams
.api4entity
,
666 action
= scope
.data
.action
|| $routeParams
.api4action
;
668 function destroyWidget() {
669 var $el
= $(element
);
670 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
671 $el
.crmDatepicker('destroy');
673 if ($el
.is('.select2-container + input')) {
674 $el
.crmEntityRef('destroy');
676 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
679 function makeWidget(field
, op
) {
680 var $el
= $(element
),
681 inputType
= field
.input_type
,
682 dataType
= field
.data_type
;
684 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
686 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
687 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
691 if (inputType
=== 'Date') {
692 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
693 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
695 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
696 if (field
.fk_entity
) {
697 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
698 } else if (field
.options
) {
699 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
700 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
702 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
703 options
.push({id
: key
, text
: val
});
705 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
707 } else if (dataType
=== 'Boolean') {
708 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
709 {id
: '1', text
: ts('Yes')},
710 {id
: '0', text
: ts('No')}
713 } else if (dataType
=== 'Integer' && !multi
) {
714 $el
.attr('type', 'number');
718 function loadFieldOptions(entity
) {
719 if (!fieldOptions
[entity
+ action
]) {
720 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
723 where
: [["options", "!=", false]],
724 select
: ["name", "options"]
727 return fieldOptions
[entity
+ action
];
730 // Copied from ng-list but applied conditionally if field is multi-valued
731 var parseList = function(viewValue
) {
732 // If the viewValue is invalid (say required but empty) it will be `undefined`
733 if (_
.isUndefined(viewValue
)) return;
742 _
.each(viewValue
.split(','), function(value
) {
743 if (value
) list
.push(_
.trim(value
));
750 // Copied from ng-list
751 ctrl
.$parsers
.push(parseList
);
752 ctrl
.$formatters
.push(function(value
) {
753 return _
.isArray(value
) ? value
.join(', ') : value
;
756 // Copied from ng-list
757 ctrl
.$isEmpty = function(value
) {
758 return !value
|| !value
.length
;
761 scope
.$watchCollection('data', function(data
) {
763 var field
= getField(data
.field
, entity
, action
);
765 makeWidget(field
, data
.op
);
773 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
776 chain
: '=api4ExpChain',
780 templateUrl
: '~/api4Explorer/Chain.html',
781 link: function (scope
, element
, attrs
) {
782 var ts
= scope
.ts
= CRM
.ts();
784 function changeEntity(newEntity
, oldEntity
) {
785 // When clearing entity remove this chain
790 // Reset action && index
791 if (newEntity
!== oldEntity
) {
792 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
794 if (getEntity(newEntity
).actions
) {
797 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
798 .then(function(data
) {
799 getEntity(data
.entity
).actions
= data
;
800 if (data
.entity
=== scope
.chain
[1][0]) {
807 function setActions() {
808 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
811 // Set default params when choosing action
812 function changeAction(newAction
, oldAction
) {
815 if (newAction
&& newAction
!== oldAction
) {
817 scope
.chain
[1][3] = '';
818 // Look for links back to main entity
819 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
820 if (field
.fk_entity
=== scope
.mainEntity
) {
821 link
= [field
.name
, '$id'];
824 // Look for links from main entity
825 if (!link
&& newAction
!== 'create') {
826 _
.each(entityFields(scope
.mainEntity
), function(field
) {
827 if (field
.fk_entity
=== scope
.chain
[1][0]) {
828 link
= ['id', '$' + field
.name
];
829 // Since we're specifying the id, set index to getsingle
830 scope
.chain
[1][3] = '0';
834 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
835 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
837 else if (link
&& _
.contains(['create'], newAction
)) {
838 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
840 else if (link
&& _
.contains(['save'], newAction
)) {
841 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
843 scope
.chain
[1][2] = '{}';
848 scope
.$watch("chain[1][0]", changeEntity
);
849 scope
.$watch("chain[1][1]", changeAction
);
854 function getEntity(entityName
) {
855 return _
.findWhere(schema
, {name
: entityName
});
858 function entityFields(entityName
, action
) {
859 var entity
= getEntity(entityName
);
860 if (entity
&& action
&& entity
.actions
) {
861 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
863 return _
.result(entity
, 'fields');
866 function getField(fieldName
, entity
, action
) {
867 var fieldNames
= fieldName
.split('.');
868 return get(entity
, fieldNames
);
870 function get(entity
, fieldNames
) {
871 if (fieldNames
.length
=== 1) {
872 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
874 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
878 var linkName
= fieldNames
.shift(),
879 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
880 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
881 return get(newEntity
, fieldNames
);
885 // Collapsible optgroups for select2
888 .on('select2-open', function(e
) {
889 if ($(e
.target
).hasClass('collapsible-optgroups')) {
891 .off('.collapseOptionGroup')
892 .addClass('collapsible-optgroups-enabled')
893 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
894 $(this).parent().toggleClass('optgroup-expanded');
898 .on('select2-close', function() {
899 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
902 })(angular
, CRM
.$, CRM
._
);