diff --git a/awx/ui/client/src/shared/directives.js b/awx/ui/client/src/shared/directives.js index f2e2b1d58d..d0435e1fc0 100644 --- a/awx/ui/client/src/shared/directives.js +++ b/awx/ui/client/src/shared/directives.js @@ -463,11 +463,51 @@ angular.module('AWDirectives', ['RestServices', 'Utilities', 'JobsHelper']) return { require: 'ngModel', link: function(scope, elm, attrs, fieldCtrl) { - let query, basePath, defer = $q.defer(); + // Auto-populating related fields when there is only 1 relatable entry isn't mission critical. + // Therefore, don't display an error message if the get request fails. + function _doAutoPopulate() { + let modelKey = attrs.ngModel; + let modelName = attrs.source; + let query = ''; + + // TODO: We can't fully rely on basePath. For example, the "Add Credentials" form sets the basePath + // to something like admin_of_organizations. Instead, we should probably just use the model name. + // At the time, we need to account for admin_of_organizations to determine if we auto-populate org + // on the cred add page. + basePath = GetBasePath(elm.attr('data-basePath')) || elm.attr('data-basePath'); + + switch(modelName) { + case 'credential': + query = '?kind=ssh'; + break; + case 'network_credential': + query = '?kind=net'; + break; + } + + Rest.setUrl(`${basePath}` + query); + Rest.get() + .success(function (data) { + // TODO: Obviously, add back in the data count + /* + if (data.count == 1) { + } + */ + scope[modelKey] = data.results[0].name; + scope[modelName] = data.results[0].id; + }); + } + + // TODO: Add more logic checks to see if this field needs to be auto-populated. Checks similar to the below linked code. + // https://github.com/ansible/ansible-tower/blob/release_3.0.3/awx/ui/client/src/lookup/lookup.factory.js#L94 + if (scope.mode === 'add') { + _doAutoPopulate(); + } + // query the API to see if field value corresponds to a valid resource // .ng-pending will be applied to the directive element while the request is outstanding // form.$pending will contain object reference to any ngModelControllers with outstanding requests diff --git a/awx/ui/client/src/shared/form-generator.js b/awx/ui/client/src/shared/form-generator.js index 7c0804d499..b257197030 100644 --- a/awx/ui/client/src/shared/form-generator.js +++ b/awx/ui/client/src/shared/form-generator.js @@ -376,6 +376,11 @@ angular.module('FormGenerator', [GeneratorHelpers.name, 'Utilities', listGenerat }, applyDefaults: function (form, scope) { + // Note: This is a hack. Ideally, mode should be set in each -.controller.js + // The mode is needed by the awlookup directive to auto-populate form fields when there is a + // single related resource. + scope.mode = this.mode; + for (var fld in form.fields) { if (form.fields[fld]['default'] || form.fields[fld]['default'] === 0) { if (form.fields[fld].type === 'select' && scope[fld + '_options']) {