Add Api4Ctrl
authorColeman Watts <coleman@civicrm.org>
Thu, 7 Feb 2019 02:46:30 +0000 (21:46 -0500)
committerCiviCRM <info@civicrm.org>
Wed, 16 Sep 2020 02:13:17 +0000 (19:13 -0700)
ext/afform/ang/afformCore.ang.php
ext/afform/ang/afformCore/Api4Ctrl.js [new file with mode: 0644]

index c8b2a48d9b67f64424f5afc4d8bf76d8cb363c39..2a0234163289dc7ccb280b0a11cfe0d97fd06076 100644 (file)
@@ -10,7 +10,7 @@ return array(
     2 => 'ang/afformCore/*/*.js',
   ),
   'css' => array(),
-  'requires' => array('crmUi', 'crmUtil'),
+  'requires' => array('crmUi', 'crmUtil', 'api4'),
   'partials' => array('ang/afformCore'),
   'settings' => array(),
   'basePages' => [],
diff --git a/ext/afform/ang/afformCore/Api4Ctrl.js b/ext/afform/ang/afformCore/Api4Ctrl.js
new file mode 100644 (file)
index 0000000..32ae530
--- /dev/null
@@ -0,0 +1,51 @@
+(function(angular, $, _) {
+
+  angular.module('afformCore').directive('affApi4Ctrl', function() {
+    return {
+      restrict: 'EA',
+      scope: {
+        affApi4Ctrl: '=',
+        affApi4: '@',
+        affApi4Refresh: '@',
+        onRefresh: '@'
+      },
+      controllerAs: 'affApi4Ctrl',
+      controller: function($scope, $parse, crmThrottle, crmApi4) {
+        var ctrl = this;
+
+        // CONSIDER: Trade-offs of upfront vs ongoing evaluation.
+        var parts = $parse($scope.affApi4)($scope.$parent);
+        ctrl.entity = parts[0];
+        ctrl.action = parts[1];
+        ctrl.params = parts[2];
+        ctrl.result = {};
+        ctrl.loading = ctrl.firstLoad = true;
+
+        ctrl.refresh = function refresh() {
+          ctrl.loading = true;
+          crmThrottle(function () {
+            return crmApi4(ctrl.entity, ctrl.action, ctrl.params)
+              .then(function (response) {
+                ctrl.result = response;
+                ctrl.loading = ctrl.firstLoad = false;
+                if ($scope.onRefresh) {
+                  $scope.$parent.$eval($scope.onRefresh, ctrl);
+                }
+              });
+          });
+        };
+
+        $scope.affApi4Ctrl = this;
+
+        var mode = $scope.affApi4Refresh ? $scope.affApi4Refresh : 'auto';
+        switch (mode) {
+          case 'auto': $scope.$watchCollection('affApi4Ctrl.params', ctrl.refresh); break;
+          case 'init': ctrl.refresh(); break;
+          case 'manual': break;
+          default: throw 'Unrecognized refresh mode: '+ mode;
+        }
+      }
+    };
+  });
+
+})(angular, CRM.$, CRM._);