Combining simple-schema, validated-method and autoform

I’am making a simple form to create recipes using this three packages and I have found a issue. I achieved to fix them but I think my solution is not the better way to fix it.

The issue come when a try to submit a form which has two hidden form field which are required. They are put with autoValue.

I had fixed it changing the restriction required to optional. This is the code:

Recipes = new Mongo.Collection('recipes');

recipeSchema = new SimpleSchema({
    name: {
        type:  String,
        label: "Name"
    },
    author: {
        type: String,
        label: "Author",
        autoValue: function() {
            return this.userId;
        },
        autoform: {
            type: "hidden"
        }
    },
    createdAt: {
        type: Date,
        label: "Created At",
        autoValue: function() {
            return new Date();
        },
        autoform: {
            type: "hidden"
        }
    }
});

Recipes.attachSchema(recipeSchema);

Recipes.methods = {};

Recipes.methods.newRecipe = new ValidatedMethod({
    name: 'Recipes.methods.newRecipe',
    validate: recipeSchema.validator(),
    run(){

    }
});


<template name="createRecipe">
    {{> quickForm collection="Recipes" id="insertRecipeForm" type="method" meteormethod="Recipes.methods.insert"}}
</template>

I think that I could create another schema to validate but I would like to know your opinion.

I know this issue is probably ancient history to you now, but have just gone through quite a bit of pain with it myself and figured I’d pass the knowledge gained on.

Your issue is due to the fact that SimpleSchema’s validator() does not by default perform a “clean” stage on the object being validated. SimpleSchema runs autoValue functions in the clean stage. So, your autoValues don’t get run during validation.

I ran into the same problem and fixed it by calling validator with { clean : true, filter : false }. These options will cause validator to run the clean stage, but still complain if extra parameters are sent in.

I’ve also written a mixin published as rlivingston:simple-schema-mixin that adds a “schema” option to ValidatedMethod to use in lieu of the “validate” option. This schema option takes a schema and calls SimpleSchema’s validator() using the above options by default.

I also see that you are using “this.userId” in an autoValue. Beware that this usage can cause great pain. If you implement server-side testing using PracticalMeteor’s mocha, you’ll likely encounter tests simply hanging with no exception anywhere and no timeout. Even if you use the ValidatedMethod _execute interface to pass in a userId, the userId will not make it into the “this” context present during validation and the insert and update operations inside your run.

3 Likes