APIv4 - Rename 'controlField' property to 'control_field' for consistency
[civicrm-core.git] / ext / afform / core / ang / af / afField.component.js
1 (function(angular, $, _) {
2 var id = 0;
3 // Example usage: <div af-fieldset="myModel"><af-field name="do_not_email" /></div>
4 angular.module('af').component('afField', {
5 require: {
6 afFieldset: '^^afFieldset',
7 afJoin: '?^^afJoin',
8 afRepeatItem: '?^^afRepeatItem'
9 },
10 templateUrl: '~/af/afField.html',
11 bindings: {
12 fieldName: '@name',
13 defn: '='
14 },
15 controller: function($scope, $element, crmApi4) {
16 var ts = $scope.ts = CRM.ts('afform'),
17 ctrl = this,
18 boolOptions = [{id: true, label: ts('Yes')}, {id: false, label: ts('No')}],
19 // Only used for is_primary radio button
20 noOptions = [{id: true, label: ''}];
21
22 this.$onInit = function() {
23 var closestController = $($element).closest('[af-fieldset],[af-join],[af-repeat-item]');
24 $scope.dataProvider = closestController.is('[af-repeat-item]') ? ctrl.afRepeatItem : ctrl.afJoin || ctrl.afFieldset;
25 $scope.fieldId = ctrl.fieldName + '-' + id++;
26
27 $element.addClass('af-field-type-' + _.kebabCase(ctrl.defn.input_type));
28
29 // is_primary field - watch others in this afRepeat block to ensure only one is selected
30 if (ctrl.fieldName === 'is_primary' && 'repeatIndex' in $scope.dataProvider) {
31 $scope.$watch('dataProvider.afRepeat.getEntityController().getData()', function (items, prev) {
32 var index = $scope.dataProvider.repeatIndex;
33 // Set first item to primary if there isn't a primary
34 if (items && !index && !_.find(items, 'is_primary')) {
35 $scope.dataProvider.getFieldData().is_primary = true;
36 }
37 // Set this item to not primary if another has been selected
38 if (items && prev && items.length === prev.length && items[index].is_primary && prev[index].is_primary &&
39 _.filter(items, 'is_primary').length > 1
40 ) {
41 $scope.dataProvider.getFieldData().is_primary = false;
42 }
43 }, true);
44 }
45
46 // ChainSelect - watch control field & reload options as needed
47 if (ctrl.defn.input_type === 'ChainSelect') {
48 $scope.$watch('dataProvider.getFieldData()[defn.input_attrs.control_field]', function(val) {
49 if (val) {
50 var params = {
51 where: [['name', '=', ctrl.fieldName]],
52 select: ['options'],
53 loadOptions: ['id', 'label'],
54 values: {}
55 };
56 params.values[ctrl.defn.input_attrs.control_field] = val;
57 crmApi4($scope.dataProvider.getEntityType(), 'getFields', params, 0)
58 .then(function(data) {
59 ctrl.defn.options = data.options;
60 });
61 }
62 });
63 }
64
65 };
66
67 $scope.getOptions = function () {
68 return ctrl.defn.options || (ctrl.fieldName === 'is_primary' && ctrl.defn.input_type === 'Radio' ? noOptions : boolOptions);
69 };
70
71 $scope.select2Options = function() {
72 return {
73 results: _.transform($scope.getOptions(), function(result, opt) {
74 result.push({id: opt.id, text: opt.label});
75 }, [])
76 };
77 };
78
79 }
80 });
81 })(angular, CRM.$, CRM._);