AutoForm 5.0.2 nested schema inputs required on update

北战南征 提交于 2019-12-04 20:25:17

I think the best solution is to add a defaultValue: [] to the address field in the schema. The behavior you described in the question (not allowing the update) is actually intended -- read on to see why.

The thing is, this behavior only exists if an array form element has already been added to the form. What I mean is, if you click the minus sign that removes the street, city, etc. inputs from the form, the update succeeds because AutoForm doesn't misinterpret the unchecked checkbox as the user explicitly unchecking the box (and therefore setting the value to false). Setting the defaultValue to an empty array lets AutoForm know to not present the address form unless the user has explicitly clicked the plus sign (i.e, they have an address they want to enter), in which case the behavior of making the street, city, etc. fields required is what you want.

Note that this means you'll have to update the existing documents in your collection that are missing the address field and set it to an empty array. Something like this in the mongo shell:

db.people.update({ "address": { $exists: false } }, { $set: { "address": [] } }, { multi: true })

You'll probably want to make sure that the query is correct by running a find on the selector first.

Edit

If the behavior you want is to show the sub-form without making it required, you can work around the checkbox issue by using the formToDoc hook and filtering out all address objects that only have the active_address field set to false (the field that AutoForm mistakenly adds for us).

AutoForm.addHooks('yourFormId', {
  formToDoc: function (doc) {
    doc.address = _.reject(doc.address, function (a) {
      return !a.street && !a.city && !a.active_address;
    });
    return doc;
  }
});

The formToDoc hook is called every time the form is validated, so you can use it to modify the doc to make it so that AutoForm is never even aware that there is an address sub-field, unless a property of it has been set. Note that if you're using this solution you won't have to add the defaultValue: [] as stated above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!