SearchKit - More efficient use of space when configuring display fields
[civicrm-core.git] / ext / search / ang / crmSearchDisplay.module.js
CommitLineData
e78d6a2d
CW
1(function(angular, $, _) {
2 "use strict";
3
4 // Declare module
03b55607
CW
5 angular.module('crmSearchDisplay', CRM.angRequires('crmSearchDisplay'))
6
406f1014 7 .factory('searchDisplayUtils', function(crmApi4) {
03b55607
CW
8
9 function replaceTokens(str, data) {
c7e96654
CW
10 if (!str) {
11 return '';
12 }
03b55607
CW
13 _.each(data, function(value, key) {
14 str = str.replace('[' + key + ']', value);
15 });
16 return str;
17 }
18
c7e96654
CW
19 function getUrl(link, row) {
20 var url = replaceTokens(link, row);
21 if (url.slice(0, 1) !== '/' && url.slice(0, 4) !== 'http') {
22 url = CRM.url(url);
23 }
24 return _.escape(url);
25 }
26
b1603dbd 27 function formatSearchValue(row, col, value) {
03b55607
CW
28 var type = col.dataType,
29 result = value;
30 if (_.isArray(value)) {
31 return _.map(value, function(val) {
ed18f50c 32 return formatSearchValue(row, col, val);
03b55607
CW
33 }).join(', ');
34 }
35 if (value && (type === 'Date' || type === 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value)) {
36 result = CRM.utils.formatDate(value, null, type === 'Timestamp');
37 }
38 else if (type === 'Boolean' && typeof value === 'boolean') {
39 result = value ? ts('Yes') : ts('No');
40 }
41 else if (type === 'Money' && typeof value === 'number') {
42 result = CRM.formatMoney(value);
43 }
44 result = _.escape(result);
45 if (col.link) {
46 result = '<a href="' + getUrl(col.link, row) + '">' + result + '</a>';
47 }
48 return result;
b1603dbd 49 }
03b55607 50
406f1014
CW
51 function getApiParams(ctrl, mode) {
52 return {
53 return: mode || 'page:' + ctrl.page,
54 savedSearch: ctrl.search,
55 display: ctrl.display,
56 sort: ctrl.sort,
57 filters: _.assign({}, (ctrl.afFieldset ? ctrl.afFieldset.getFieldData() : {}), ctrl.filters)
58 };
59 }
60
61 function getResults(ctrl) {
62 var params = getApiParams(ctrl);
63 crmApi4('SearchDisplay', 'run', params).then(function(results) {
64 ctrl.results = results;
65 if (ctrl.settings.pager && !ctrl.rowCount) {
66 if (results.length < ctrl.settings.limit) {
67 ctrl.rowCount = results.length;
68 } else {
69 var params = getApiParams(ctrl, 'row_count');
70 crmApi4('SearchDisplay', 'run', params).then(function(result) {
71 ctrl.rowCount = result.count;
72 });
73 }
b1603dbd
CW
74 }
75 });
b1603dbd
CW
76 }
77
78 return {
79 formatSearchValue: formatSearchValue,
406f1014
CW
80 getApiParams: getApiParams,
81 getResults: getResults,
c7e96654 82 replaceTokens: replaceTokens
03b55607
CW
83 };
84 });
e78d6a2d
CW
85
86})(angular, CRM.$, CRM._);