1 (function(angular
, $, _
) {
3 // Example usage: <div af-fieldset="myModel"><af-field name="do_not_email" /></div>
4 angular
.module('af').component('afField', {
6 afFieldset
: '^^afFieldset',
8 afRepeatItem
: '?^^afRepeatItem'
10 templateUrl
: '~/af/afField.html',
15 controller: function($scope
, $element
, crmApi4
) {
16 var ts
= $scope
.ts
= CRM
.ts('afform'),
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
: ''}];
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
++;
27 $element
.addClass('af-field-type-' + _
.kebabCase(ctrl
.defn
.input_type
));
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;
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
41 $scope
.dataProvider
.getFieldData().is_primary
= false;
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
) {
51 where
: [['name', '=', ctrl
.fieldName
]],
53 loadOptions
: ['id', 'label'],
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
;
67 $scope
.getOptions = function () {
68 return ctrl
.defn
.options
|| (ctrl
.fieldName
=== 'is_primary' && ctrl
.defn
.input_type
=== 'Radio' ? noOptions
: boolOptions
);
71 $scope
.select2Options = function() {
73 results
: _
.transform($scope
.getOptions(), function(result
, opt
) {
74 result
.push({id
: opt
.id
, text
: opt
.label
});
81 })(angular
, CRM
.$, CRM
._
);