Commit | Line | Data |
---|---|---|
65d7084b CW |
1 | (function(angular, $, _) { |
2 | // Example usage: <af-form ctrl="afform"> | |
3 | angular.module('af').component('afForm', { | |
4 | bindings: { | |
5 | ctrl: '@' | |
6 | }, | |
31c51d71 | 7 | controller: function($scope, $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() { | |
31c51d71 CW |
38 | var toLoad = 0, |
39 | args = $scope.$parent.routeParams || {}; | |
65d7084b | 40 | _.each(schema, function(entity, entityName) { |
31c51d71 | 41 | if (args[entityName] || entity.autofill) { |
65d7084b CW |
42 | toLoad++; |
43 | } | |
44 | }); | |
45 | if (toLoad) { | |
31c51d71 | 46 | crmApi4('Afform', 'prefill', {name: ctrl.getFormMeta().name, args: args}) |
65d7084b CW |
47 | .then(function(result) { |
48 | _.each(result, function(item) { | |
49 | data[item.name] = data[item.name] || {}; | |
50 | _.extend(data[item.name], item.values, schema[item.name].data || {}); | |
51 | }); | |
52 | }); | |
53 | } | |
54 | }; | |
55 | ||
56 | this.submit = function submit() { | |
31c51d71 | 57 | var submission = crmApi4('Afform', 'submit', {name: ctrl.getFormMeta().name, args: $scope.$parent.routeParams || {}, values: data}); |
b6e13973 SL |
58 | var metaData = ctrl.getFormMeta(); |
59 | if (metaData.redirect) { | |
60 | submission.then(function() { | |
61 | var url = metaData.redirect; | |
62 | if (url.indexOf('civicrm/') === 0) { | |
63 | url = CRM.url(url); | |
64 | } else if (url.indexOf('/') === 0) { | |
65 | url = $location.protocol() + '://' + $location.host() + url; | |
66 | } | |
67 | $window.location.href = url; | |
68 | }); | |
69 | } | |
65d7084b CW |
70 | return crmStatus({start: ts('Saving'), success: ts('Saved')}, submission); |
71 | }; | |
72 | } | |
73 | }); | |
74 | })(angular, CRM.$, CRM._); |