简体   繁体   中英

Meteor, autoform, pre filling input

Been struggling with an autoform to pre-fill the data, especially in hidden fields.

I have tried many things including using autoValue and defaultValue, but autoValue is validated on the server side and I need to grab a value from the page on the client side (the Router current route name) so it fails when getting looked up in the .clean function, and defaultValue takes a value, and won't take a function.

How to pass a value to a form to pre-fill some fields, without showing the field?

So, I posted the question because I have struggled and found the answer and wanted to share.

In the end, you can pass a doc attribute to a form in the form it looks like:

{{> quickform 
   collection"mycollection" 
   id="formid" 
   type="method" 
   ...
   doc=mydoc
}}

and then you need a template helper to create the doc:

Template.myform_template.helper({
   mydoc: function() {
      return {field1: value1, field2:value2 };
   }
})

You don't have to fill all the fields, just the one you want to pre-fill, just like the way the 'update' form works.

In order NOT to show this value in the form, I had tried to use the omitFields attribute, but that does not work as the field in the doc gets removed. so the only way I found was to declare the type of field in the schema as 'hidden' with

mycollection.attachSchema(new SimpleSchema({
   field1: {
       type: String,
       optional: false,
       autoform: {
            type: "hidden"
       }
   }
}))

and here you are.

Now, on calling schema.clean(doc) in the method, the value is not really 'validated' since there is nothing to validate against in the schema, so you should validate those values yourself in the method call.

when i need prefill fields for an atoform, i use the AutoFom.hooks and in the template.html file i don't add these fields.

TemplateFile.html

{{#autoForm schema="Schemas.Myschema" id="idForm" resetOnSuccess="true"  type="method" meteormethod="server/insertCustomizedTemplate"}}

{{> afQuickField name='Field1'}}
{{> afQuickField name='Field2'}}
{{> afQuickField name='Field3'}}

<button href="" type="submit" class="btn btn-success">
  Send
</button>

{{/autoForm}}

TemplateFile.js

AutoForm.hooks({
    idForm: {
        before: {
            method: function(doc) {
                doc.Dummyfield1 = 'Harcoded Value';
                doc.Dummyfield2 = 'Harcoded Value';

                return doc;
            }
        },
        onSuccess: function(formType, result) {

        },
        onError: function(formType, error) {
        }
    }
});

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