Meteor-Community-Packages / meteor-simple-schema

Meteor integration package for simpl-schema
https://github.com/Meteor-Community-Packages/meteor-simple-schema
MIT License
919 stars 161 forks source link

How to preserve empty array fields? #695

Closed draftomatic closed 7 years ago

draftomatic commented 7 years ago

When minCount is 0 and there are no items in the array, the field is completely removed/unset from the resulting object. I would like it to submit an empty array.

This doesn't work but it illustrates my goal:

'variables.myObjectArray': {
    type: [MyObjectSchema],
    label: 'An Object',
    minCount: 0,
    maxCount: 10,
    autoValue: function() {
        if (!this.isSet) {
            return [];
        }
    }
}

When myObjectArray is empty in the form, I want it to submit:

variables: {
    myObjectArray: []
}

How do I force SimpleSchema/AutoForm to preserve empty arrays in the resulting object?

aldeed commented 7 years ago

hmm, off the top of my head I'm not sure if this is actually possible. You might try defining the array item separately because when you use the type: [] shorthand, I think it guesses that you want that autoValue on the items rather than on the array itself.

'variables.myObjectArray': {
    type: Array,
    label: 'An Object',
    minCount: 0,
    maxCount: 10,
    autoValue: function() {
        if (!this.isSet) {
            return [];
        }
    }
},
'variables.myObjectArray.$': {
    type: MyObjectSchema
}
draftomatic commented 7 years ago

Thanks I tried your advice - doesn't appear to help. I suppose I'll have to add some ugly ad-hoc code to put the empty arrays back in after cleaning/validating.

draftomatic commented 7 years ago

Revisited this and the autoValue technique does indeed give me the empty array after cleaning. I was printing in the wrong place. Sorry for the trouble and thanks for the help!