简体   繁体   中英

Meteor AutoForm set optional field to be required

I've the following (simplified) SimpleSchema:

EventSchema = new SimpleSchema({
    eventType: {
        type: String
    },
    kicker: {
        type: String
    },
    kicker2: {
        type: String,
        optional: true
    }
});

With this I'm using AutoForm to generate a insert form. Here is a simplified version of it:

{{#autoForm schema="EventSchema" type="method" meteormethod="addEvent"}}
    {{> afFieldInput name="eventType" options=getSubstitutionEventTypes type="select-radio-inline"}}

    {{> afFieldInput name="kicker" type="select" options=this}}

    {{> afFieldInput name="kicker2" type="select" options=this}}
{{/autoForm}}

As I'm using this Schema in an other autoForm where I don't have to input "kicker2", I've set this field to be optional. But in the form mentioned above, this field is required too. So how can I override the optional setting for a field in a specific form?

I've already tried the following, but it didn't work (required isn't rendered in the HTML):

{{> afFieldInput name="kicker2" type="select" options=this required="required"}}

Thanks in advance!

You have some tricks to have an optional value depending on situations, a nice one would be to set the optional value on the return of a function, giving something like this:

EventSchema = new SimpleSchema({
    eventType: {
        type: String
    },
    kicker: {
        type: String
    },
    kicker2: {
        type: String,
        optional: function() {
            return (! this.isInsert)
        }
    }
});

So it is optional on update but not on insert (you can use whatever means to customize it). Another way to have different validation rules between forms is simply by creating a specific schema for a given form and then having autoForm(schema=yourSpecificSchema ... instead of autoForm(collection="Meteor.users" . Do not forget to register an helper so your schema is accessible from your form. You can refer on the official documentation for more details: https://github.com/aldeed/meteor-autoform#non-collection-forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM