dev/core#2522 Add in Submit Action and redirect handling post form submit
[civicrm-core.git] / ext / afform / core / ang / af / afForm.component.js
CommitLineData
65d7084b
CW
1(function(angular, $, _) {
2 // Example usage: <af-form ctrl="afform">
3 angular.module('af').component('afForm', {
4 bindings: {
5 ctrl: '@'
6 },
b6e13973 7 controller: function($scope, $routeParams, $timeout, crmApi4, crmStatus, $window, $location) {
65d7084b
CW
8 var schema = {},
9 data = {},
10 ctrl = this;
11
65d7084b 12 this.$onInit = function() {
652d6cee
CW
13 // This component has no template. It makes its controller available within it by adding it to the parent scope.
14 $scope.$parent[this.ctrl] = this;
15
65d7084b
CW
16 $timeout(ctrl.loadData);
17 };
18
19 this.registerEntity = function registerEntity(entity) {
20 schema[entity.modelName] = entity;
21 data[entity.modelName] = [];
22 };
23 this.getEntity = function getEntity(name) {
24 return schema[name];
25 };
26 // Returns field values for a given entity
27 this.getData = function getData(name) {
28 return data[name];
29 };
30 this.getSchema = function getSchema(name) {
31 return schema[name];
32 };
33 // Returns the 'meta' record ('name', 'description', etc) of the active form.
34 this.getFormMeta = function getFormMeta() {
35 return $scope.$parent.meta;
36 };
37 this.loadData = function() {
38 var toLoad = 0;
39 _.each(schema, function(entity, entityName) {
40 if ($routeParams[entityName] || entity.autofill) {
41 toLoad++;
42 }
43 });
44 if (toLoad) {
45 crmApi4('Afform', 'prefill', {name: ctrl.getFormMeta().name, args: $routeParams})
46 .then(function(result) {
47 _.each(result, function(item) {
48 data[item.name] = data[item.name] || {};
49 _.extend(data[item.name], item.values, schema[item.name].data || {});
50 });
51 });
52 }
53 };
54
55 this.submit = function submit() {
56 var submission = crmApi4('Afform', 'submit', {name: ctrl.getFormMeta().name, args: $routeParams, values: data});
b6e13973
SL
57 var metaData = ctrl.getFormMeta();
58 if (metaData.redirect) {
59 submission.then(function() {
60 var url = metaData.redirect;
61 if (url.indexOf('civicrm/') === 0) {
62 url = CRM.url(url);
63 } else if (url.indexOf('/') === 0) {
64 url = $location.protocol() + '://' + $location.host() + url;
65 }
66 $window.location.href = url;
67 });
68 }
65d7084b
CW
69 return crmStatus({start: ts('Saving'), success: ts('Saved')}, submission);
70 };
71 }
72 });
73})(angular, CRM.$, CRM._);