Merge pull request #18876 from colemanw/searchDisplay
[civicrm-core.git] / ext / search / ang / crmSearchActions / crmSearchActionUpdate.ctrl.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('crmSearchActions').controller('crmSearchActionUpdate', function ($scope, $timeout, crmApi4, dialogService) {
5 var ts = $scope.ts = CRM.ts(),
6 model = $scope.model,
7 ctrl = $scope.$ctrl = this;
8
9 this.entityTitle = model.ids.length === 1 ? model.entityInfo.title : model.entityInfo.title_plural;
10 this.values = [];
11 this.add = null;
12 this.fields = null;
13
14 crmApi4(model.entity, 'getFields', {action: 'update', loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon']})
15 .then(function(fields) {
16 ctrl.fields = fields;
17 });
18
19 this.updateField = function(index) {
20 // Debounce the onchange event using timeout
21 $timeout(function() {
22 if (!ctrl.values[index][0]) {
23 ctrl.values.splice(index, 1);
24 }
25 });
26 };
27
28 this.addField = function() {
29 // Debounce the onchange event using timeout
30 $timeout(function() {
31 if (ctrl.add) {
32 ctrl.values.push([ctrl.add, '']);
33 }
34 ctrl.add = null;
35 });
36 };
37
38 this.getField = function(fieldName) {
39 return _.where(ctrl.fields, {name: fieldName})[0];
40 };
41
42 function fieldInUse(fieldName) {
43 return _.includes(_.collect(ctrl.values, 0), fieldName);
44 }
45
46 this.availableFields = function() {
47 var results = _.transform(ctrl.fields, function(result, item) {
48 var formatted = {id: item.name, text: item.label, description: item.description};
49 if (fieldInUse(item.name)) {
50 formatted.disabled = true;
51 }
52 if (item.name !== 'id') {
53 result.push(formatted);
54 }
55 }, []);
56 return {results: results};
57 };
58
59 this.cancel = function() {
60 dialogService.cancel('crmSearchAction');
61 };
62
63 this.save = function() {
64 crmApi4(model.entity, 'Update', {
65 where: [['id', 'IN', model.ids]],
66 values: _.zipObject(ctrl.values)
67 }).then(function() {
68 dialogService.close('crmSearchAction');
69 });
70 };
71
72 });
73 })(angular, CRM.$, CRM._);