Skip to content

Feature: clean model when a field is removed from view, such as when a condition is no longer satisfied. #371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ Angular Schema Form

Generate forms from JSON schemas using AngularJS!

Web Page / Twitter
The Web Site / The Twitter / The Movie
--------
[schemaform.io](http://schemaform.io) / [@SchemaFormIO](http://twitter.com/SchemaFormIO)
[schemaform.io](http://schemaform.io) / [@SchemaFormIO](http://twitter.com/SchemaFormIO) / [Movie](https://www.youtube.com/watch?v=duBFMipRq2o)

Demo Time!
----------
Expand Down
23 changes: 14 additions & 9 deletions src/directives/schema-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ FIXME: real documentation

angular.module('schemaForm')
.directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect', 'sfPath',
function($compile, schemaForm, schemaFormDecorators, sfSelect, sfPath) {
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect', 'sfPath', 'sfRetainModel',
function($compile, schemaForm, schemaFormDecorators, sfSelect, sfPath, sfRetainModel) {

var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function(name, separator) {
Expand Down Expand Up @@ -119,14 +119,16 @@ angular.module('schemaForm')
$compile(element.children())(childScope);

//ok, now that that is done let's set any defaults
schemaForm.traverseSchema(schema, function(prop, path) {
if (angular.isDefined(prop['default'])) {
var val = sfSelect(path, scope.model);
if (angular.isUndefined(val)) {
sfSelect(path, scope.model, prop['default']);
if (!scope.options || scope.options.setSchemaDefaults !== false) {
schemaForm.traverseSchema(schema, function(prop, path) {
if (angular.isDefined(prop['default'])) {
var val = sfSelect(path, scope.model);
if (angular.isUndefined(val)) {
sfSelect(path, scope.model, prop['default']);
}
}
}
});
});
}

scope.$emit('sf-render-finished', element);
};
Expand Down Expand Up @@ -159,6 +161,9 @@ angular.module('schemaForm')
}
});

scope.$on('$destroy', function() {
sfRetainModel.setFlag(true);
});
}
};
}
Expand Down
84 changes: 45 additions & 39 deletions src/directives/schema-validate.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', 'sfSelect', 'sfUnselect',
function(sfValidator, sfSelect, sfUnselect) {
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', 'sfSelect', 'sfUnselect', '$parse', 'sfRetainModel',
function(sfValidator, sfSelect, sfUnselect, $parse, sfRetainModel) {

return {
restrict: 'A',
Expand Down Expand Up @@ -127,54 +127,60 @@ angular.module('schemaForm').directive('schemaValidate', ['sfValidator', 'sfSele
// Clean up the model when the corresponding form field is $destroy-ed.
// Default behavior can be supplied as a globalOption, and behavior can be overridden in the form definition.
scope.$on('$destroy', function() {
var form = getForm();

// Either set in form definition, or as part of globalOptions.
var destroyStrategy =
!form.hasOwnProperty('destroyStrategy') ? DEFAULT_DESTROY_STRATEGY : form.destroyStrategy;
var schemaType = getSchemaType();

if (destroyStrategy && destroyStrategy !== 'retain' ) {
// Don't recognize the strategy, so give a warning.
console.warn('%s has defined unrecognized destroyStrategy: \'%s\'. Used default instead.',
attrs.name, destroyStrategy);
destroyStrategy = DEFAULT_DESTROY_STRATEGY;
}
else if (schemaType !== 'string' && destroyStrategy === '') {
// Only 'string' type fields can have an empty string value as a valid option.
console.warn('%s attempted to use empty string destroyStrategy on non-string form type. ' +
'Used default instead.', attrs.name);
destroyStrategy = DEFAULT_DESTROY_STRATEGY;
}
var form = getForm();
var conditionResult = $parse(form.condition);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was looking through the code and testing some, and I'm not quite sure why we need to check on the condition here? Shouldn't we always just follow the destroy strategy if we get a destroy event? I'm thinking that condition might not be the only thing that can remove a form element from the form, any other add on might use a ng-if somewhere and since any field not in the DOM won't get any validation done on it anyways It's probably best to remove it from the model.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had left it in as a way to help show where I was coming from with my solution, because I wasn't 100% confident that the service I put in would be correct (I'd still label myself an apprentice with Javascript). Assuming that the flag will handle for the case where the destroy is coming from outside of the form, then I agree that destroys initiated within the form should just follow the destroyStrategy. It'll be more consistent (and still configurable) and easier to explain.

var formModelNotRetained = !sfRetainModel.getFlag();

// If condition is defined and not satisfied and the sfSchema model should not be retained.
if (form.hasOwnProperty('condition') && !conditionResult(scope) && formModelNotRetained) {

// Either set in form definition, or as part of globalOptions.
var destroyStrategy =
!form.hasOwnProperty('destroyStrategy') ? DEFAULT_DESTROY_STRATEGY : form.destroyStrategy;
var schemaType = getSchemaType();

if (destroyStrategy && destroyStrategy !== 'retain') {
// Don't recognize the strategy, so give a warning.
console.warn('%s has defined unrecognized destroyStrategy: \'%s\'. Used default instead.',
attrs.name, destroyStrategy);
destroyStrategy = DEFAULT_DESTROY_STRATEGY;
}
else if (schemaType !== 'string' && destroyStrategy === '') {
// Only 'string' type fields can have an empty string value as a valid option.
console.warn('%s attempted to use empty string destroyStrategy on non-string form type. ' +
'Used default instead.', attrs.name);
destroyStrategy = DEFAULT_DESTROY_STRATEGY;
}

if (destroyStrategy === 'retain') {
return; // Valid option to avoid destroying data in the model.
}
if (destroyStrategy === 'retain') {
return; // Valid option to avoid destroying data in the model.
}

destroyUsingStrategy(destroyStrategy);
destroyUsingStrategy(destroyStrategy);

function destroyUsingStrategy(strategy) {
var strategyIsDefined = (strategy === null || strategy === '' || strategy === undefined);
if (!strategyIsDefined){
strategy = DEFAULT_DESTROY_STRATEGY;
function destroyUsingStrategy(strategy) {
var strategyIsDefined = (strategy === null || strategy === '' || strategy === undefined);
if (!strategyIsDefined) {
strategy = DEFAULT_DESTROY_STRATEGY;
}
sfUnselect(scope.form.key, scope.model, strategy);
}
sfUnselect(scope.form.key, scope.model, strategy);
}

function getSchemaType() {
var sType;
if (form.schema) {
sType = form.schema.type;
function getSchemaType() {
var sType;
if (form.schema) {
sType = form.schema.type;
}
else {
sType = null;
}
return sType;
}
else {
sType = null;
}
return sType;
}
});



scope.schemaError = function() {
return error;
};
Expand Down
37 changes: 37 additions & 0 deletions src/services/retainModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
angular.module('schemaForm').factory('sfRetainModel', function() {

var data = {retainModelFlag: false };

return {
/**
* @description
* Utility service to indicate if the sfSchema model should be retained.
* Set to true to prevent an operation that would have destroyed the model
* from doing so (such as wrapping the form in an ng-if).
*
* ex.
* var foo = sfRetainModel.getFlag();
*
* @returns {boolean} returns the current value of the retainModelFlag.
*/
getFlag: function () {
return data.retainModelFlag;
},

/**
* @description
* Set the value of the retainModelFlag.
* True prevents cleaning the data in the model, while false follows the configured destroyStrategy.
*
* ex.
* var bar = sfRetainModel.setFlag(true);
*
* @param {boolean} value The boolean value to set as the retainModelFlag
* @returns {boolean} returns the value of the retainModelFlag after toggling.
*/
setFlag: function(value) {
data.retainModelFlag = value;
return data.retainModelFlag;
}
}
});
48 changes: 45 additions & 3 deletions test/directives/schema-form-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,48 @@ describe('directive',function(){
});
});

it('should honor defaults in schema unless told not to',function(){

inject(function($compile,$rootScope){
var scope = $rootScope.$new();
scope.person = {
name: 'Foobar'
};

scope.schema = {
"type": "object",
"properties": {
"name": {
"type": "string",
"default": "Bar"
},
"nick": {
"type": "string",
"default": "Zeb"
},
"alias": {
"type": "string"
},
}
};

scope.form = ["*"];

scope.options = {setSchemaDefaults: false};

var tmpl = angular.element('<form sf-options="options" sf-schema="schema" sf-form="form" sf-model="person"></form>');

$compile(tmpl)(scope);
$rootScope.$apply();

scope.person.name.should.be.equal('Foobar');
expect(scope.person.nick).to.be.undefined;
expect(scope.person.alias).to.be.undefined;

});
});


it('should handle schema form default in deep structure',function(){

inject(function($compile,$rootScope){
Expand Down Expand Up @@ -1950,7 +1992,7 @@ describe('directive',function(){
}
};
scope.form = [field.form];

var tmpl = angular.element('<form name="theForm" sf-schema="schema" sf-form="form" sf-model="model"></form>');
$compile(tmpl)(scope);
$rootScope.$apply();
Expand Down Expand Up @@ -1978,7 +2020,7 @@ describe('directive',function(){
}
};
scope.form = [field.form];

var tmpl = angular.element('<form name="theForm" sf-schema="schema" sf-form="form" sf-model="model"></form>');
$compile(tmpl)(scope);
$rootScope.$apply();
Expand All @@ -1993,4 +2035,4 @@ describe('directive',function(){
});
});
});
});
});