Form events such as onSubmit
currently only passes doc
but there are cases where a modifier
is more suitable, especially for update
forms
Consider a schema where all the fields are optional
collection = new Mongo.Collection('sample')
schema = new SimpleSchema({
foo: {type: String, optional: true},
bar: {type: String, optional: true},
})
collection.attachSchema(schema)
and consider this document:
doc = {
foo: "some value"
}
<AutoForm onSubmit={ doc => collection.update( this.props.docId, { $set: {...doc} } ) } model={doc} schema={schema} />
Now if you delete the value of foo and submit, this will throw error saying that after filtering out, modifier is empty.
This is expected because collection2
trims trailing spaces, deletes empty fields, runs autovalues etc before doing the actual insert, at which time doc
becomes {}
so instead, we need to $unset: { foo: '' }
so to mitigate this, I am currently doing this:
function handler(docId,doc) {
const unsetDoc = schema.objectKeys
.filter( key => !doc[key] )
.map( key => ( {[key]: ''} ) )
.reduce( (obj, unset) => {
obj[Object.keys(unset)[0]] = unset[Object.keys(unset)[0]];
return obj;
}, {} );
let modifier = {};
if (Object.keys(doc).length > 0) {
modifier.$set = {...doc}
}
if (Object.keys(unsetDoc).length > 0) {
modifier.$unset = {...unsetDoc}
}
collection.update(docId, modifier);
}
But it would be awesome if onSubmit
were able to provide me the modifier
out of box, such that, the following would work:
<AutoForm
onSubmit={ (doc,modifier) => handler(this.props.docId, modifier) }
model={doc}
schema={schema} />
Now the original autoform has solutions similar to this:
- update form automatically handles this, providing a modifier and passing it on to the collection
- method update form which provides you a modifier and document id which you can pass on to your methods
- hooks where
onSubmit
passes a doc and a modifier and a formToModifier
hook which directly takes the modifier whenever form fields change (like an onChange
for update forms)
For code reference, you can take a look at here and here