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 | }, | |
7 | controller: function($scope, $routeParams, $timeout, crmApi4, crmStatus) { | |
8 | var schema = {}, | |
9 | data = {}, | |
10 | ctrl = this; | |
11 | ||
12 | // This component has no template. It makes its controller available within it by adding it to the parent scope. | |
13 | $scope.$parent[this.ctrl] = this; | |
14 | ||
15 | this.$onInit = function() { | |
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}); | |
57 | return crmStatus({start: ts('Saving'), success: ts('Saved')}, submission); | |
58 | }; | |
59 | } | |
60 | }); | |
61 | })(angular, CRM.$, CRM._); |