1 (function(angular
, $, _
) {
2 // Example usage: <af-form ctrl="afform">
3 angular
.module('af').component('afForm', {
7 controller: function($scope
, $element
, $timeout
, crmApi4
, crmStatus
, $window
, $location
, FileUploader
) {
14 this.$onInit = function() {
15 // This component has no template. It makes its controller available within it by adding it to the parent scope.
16 $scope
.$parent
[this.ctrl
] = this;
18 $timeout(ctrl
.loadData
);
21 this.registerEntity
= function registerEntity(entity
) {
22 schema
[entity
.modelName
] = entity
;
23 data
[entity
.modelName
] = [];
25 this.getEntity
= function getEntity(name
) {
28 // Returns field values for a given entity
29 this.getData
= function getData(name
) {
32 this.getSchema
= function getSchema(name
) {
35 // Returns the 'meta' record ('name', 'description', etc) of the active form.
36 this.getFormMeta
= function getFormMeta() {
37 return $scope
.$parent
.meta
;
39 this.loadData = function() {
41 args
= _
.assign({}, $scope
.$parent
.routeParams
|| {}, $scope
.$parent
.options
|| {});
42 _
.each(schema
, function(entity
, entityName
) {
43 if (args
[entityName
] || entity
.autofill
) {
48 crmApi4('Afform', 'prefill', {name
: ctrl
.getFormMeta().name
, args
: args
})
49 .then(function(result
) {
50 _
.each(result
, function(item
) {
51 data
[item
.name
] = data
[item
.name
] || {};
52 _
.extend(data
[item
.name
], item
.values
, schema
[item
.name
].data
|| {});
58 // Used when submitting file fields
59 this.fileUploader
= new FileUploader({
60 url
: CRM
.url('civicrm/ajax/api4/Afform/submitFile'),
61 headers
: {'X-Requested-With': 'XMLHttpRequest'},
62 onCompleteAll
: postProcess
,
63 onBeforeUploadItem: function(item
) {
65 status
= CRM
.status({start
: ts('Uploading %1', {1: item
.file
.name
})});
69 // Called after form is submitted and files are uploaded
70 function postProcess() {
71 var metaData
= ctrl
.getFormMeta(),
72 dialog
= $element
.closest('.ui-dialog-content');
74 $element
.trigger('crmFormSuccess', {
83 dialog
.dialog('close');
86 else if (metaData
.redirect
) {
87 var url
= metaData
.redirect
;
88 if (url
.indexOf('civicrm/') === 0) {
90 } else if (url
.indexOf('/') === 0) {
91 url
= $location
.protocol() + '://' + $location
.host() + url
;
93 $window
.location
.href
= url
;
97 this.submit = function() {
98 status
= CRM
.status({});
101 crmApi4('Afform', 'submit', {
102 name
: ctrl
.getFormMeta().name
,
105 ).then(function(response
) {
106 if (ctrl
.fileUploader
.getNotUploadedItems().length
) {
107 _
.each(ctrl
.fileUploader
.getNotUploadedItems(), function(file
) {
109 params
: JSON
.stringify(_
.extend({
110 token
: response
[0].token
,
111 name
: ctrl
.getFormMeta().name
112 }, file
.crmApiParams()))
115 ctrl
.fileUploader
.uploadAll();
123 })(angular
, CRM
.$, CRM
._
);