AutoForm

repository·devel·Indexed 23 days ago

https://github.com/meteor-community-packages/meteor-autoform

A Meteor package that automates form creation by providing UI components, automatic collection insert/update events, and reactive validation based on schemas. It integrates with simpl-schema (required for v6+) and optionally collection2. The package provides helpers like quickForm for rapid generation and autoForm for custom layouts, along with decoupled theme support starting in version 7.0.

Tokens
16.5K
Snippets
25
Records
102
Agent score
78%

What's inside meteor-autoform

  1. What is AutoForm?

    devel

    AutoForm is a Meteor package designed to simplify form creation. It provides:

    • UI Components: Helpers to build forms quickly.
    • Automatic Events: Handles automatic insert and update events for Meteor collections.
    • Reactive Validation: Automatically validates form inputs based on a schema.

    It works best when paired with a schema library like simpl-schema (required for v6+) and can be used with collection2 for enhanced collection integration.

  2. AutoForm 7.0 Breaking Changes

    devel

    AutoForm 7.0 introduces a major change by decoupling from default themes.

    Key Change:

    • You are now responsible for installing themes manually. If you upgrade to 7.0 without adding a theme package, your forms may not render correctly.

    Note for Add-on Package Users: If you use community add-on packages, ensure they have been updated for AutoForm 7.0 before upgrading. If an add-on is not yet compatible, you should stay on version 6.x.

  3. How to organize and provide schemas to AutoForm

    devel

    When using the schema attribute in {{#autoForm}}, you can provide the schema in two ways:

    1. Using Quotation Marks: If you use schema="MySchema", AutoForm looks for an object named MySchema in the global window scope. This works if your schemas are defined at the top level of client files without the var keyword.
    2. Using Helpers (Recommended): If you don't use quotation marks, you must define a Meteor helper that returns the SimpleSchema instance.

    Best Practice: Add all SimpleSchema instances to a central Schemas object and register that object as a helper to keep your code organized.

    // common.js
    Schemas = {};
    Schemas.ContactForm = new SimpleSchema({
      name: { type: String, label: "Your name" },
      // ...
    });
    
    // client.js
    Template.registerHelper("Schemas", Schemas);
    <template name="contactForm">
      {{#autoForm schema=Schemas.ContactForm id="contactForm" type="method" meteormethod="sendEmail"}}
      {{/autoForm}}
    </template>
  4. Transform form data using formToDoc and docToForm

    devel

    If your UI input format differs from your database storage format (e.g., a comma-separated string in a text field vs. an array in the database), use formToDoc and docToForm hooks.

    Workflow:

    1. Define the correct type in your SimpleSchema (e.g., type: [String]).
    2. Use docToForm to convert the database array into a string for the input field.
    3. Use formToDoc to convert the input string back into an array before it hits the database.

    Note: For update forms, use formToModifier instead of formToDoc.

    {{> afFieldInput name="tags" type="text"}}
    AutoForm.hooks({
      postsForm: {
        docToForm: function(doc) {
          if (Array.isArray(doc.tags)) {
            doc.tags = doc.tags.join(", ");
          }
          return doc;
        },
        formToDoc: function(doc) {
          if (typeof doc.tags === "string") {
            doc.tags = doc.tags.split(",");
          }
          return doc;
        }
      }
    });
  5. Map inputs to subdocuments using dot notation

    devel

    AutoForm supports MongoDB dot notation in field names to automatically map input values to nested objects or arrays in your document.

    • Subdocuments: Use address.street to map to doc.address.street.
    • Arrays: Use addresses.1.street to map to the street property of the object at index 1 in the doc.addresses array.
    {{> afFieldInput 'address.street'}}
    {{> afFieldInput 'addresses.1.street'}}
  6. Handle Object and Array fields in AutoForm

    devel

    AutoForm provides specialized components for fields with Object or Array types to manage nested data structures.

    Object Fields

    When using afQuickField for an Object type, it defaults to the afObjectField component. This component renders all subfields as a single group, typically labeled with the object field's name. In the bootstrap3 theme, this appears as a panel with a heading.

    Array Fields

    When using afQuickField for an Array type, it defaults to the afArrayField component. This component:

    • Renders array items as a group labeled with the array field's name.
    • Automatically provides UI buttons for adding and removing items.
    • Supports minCount, maxCount, and initialCount attributes to control the number of items.

    Constraints on counts:

    • You cannot set minCount lower than the schema-defined minimum.
    • You cannot set maxCount higher than the schema-defined maximum.
    • minCount takes precedence over initialCount. If minCount is 1 and initialCount is 0, the initial count will be 1.

    To specify options for every item within an array, use the following schema syntax:

    'arrayFieldName.$': {
      ... 
      autoform: {
        afFieldInput: {
          options: function () {
            // return options object
          }
        }
      }
    }
  7. Group fields using fieldsets in schemas

    devel

    The plain, bootstrap, and bootstrap-horizontal quickForm templates allow you to group fields into fieldsets by adding a group property to the field configuration in your schema.

    Example schema configuration:

    {
      autoform: {
        group: 'Contact Information'
      }
    }

    Fields with the same group name will be wrapped in a <fieldset> with a <legend> containing the group name. Fieldsets appear below any fields that do not specify a group.

    CSS Classes:

    • Fieldset: af-fieldGroup
    • Legend: af-fieldGroup-heading

    Note: This feature only affects quickForm templates.

  8. Customize array rendering with afEachArrayItem

    devel

    The afEachArrayItem block helper allows you to reactively render custom content for each item in an array. It tracks the addition and removal of array items or groups of fields automatically. This is most useful when building custom afArrayField templates.

    Inside an afEachArrayItem block, you can use the following helpers to determine the position of the current item:

    • afArrayFieldIsFirstVisible: Returns true if the current item is the first visible item in the array.
    • afArrayFieldIsLastVisible: Returns true if the current item is the last visible item in the array.
  9. Migrate from AutoForm 6.x to 7.0.0

    devel

    When upgrading to version 7.0.0, you may encounter package version conflicts in Meteor because existing extension packages might still reference version 6.x in their constraints.

    To resolve this, edit your .meteor/packages file and change aldeed:autoform to aldeed:autoform@7.0.0! (adding an exclamation mark). This forces the use of version 7.0.0 despite the constraints in extension packages. Version 7.0.0 is designed to maintain compatibility with 6.x extensions.

  10. Use onSubmit hooks for custom submission logic

    devel

    The normal form type allows you to define custom submission logic using AutoForm.hooks.

    When an onSubmit hook is triggered, it receives three arguments:

    1. insertDoc: The cleaned and validated form values (suitable for insert()). Note: auto/default values are not yet added.
    2. updateDoc: The form input values as a modifier (not validated).
    3. currentDoc: The object currently bound to the form via the doc attribute.

    Important Requirements:

    • You must call this.done() when your custom logic is finished.
    • If you perform asynchronous tasks, call this.done(error) to trigger onError hooks, or this.done(null, result) to trigger onSuccess hooks.
    • If you return false, the default browser submission is prevented.
    • To add auto/default values to insertDoc or updateDoc manually on the client, use Schema.clean(doc).
    AutoForm.hooks({
      contactForm: {
        onSubmit: function (insertDoc, updateDoc, currentDoc) {
          if (customHandler(insertDoc)) {
            this.done();
          } else {
            this.done(new Error("Submission failed"));
          }
          return false;
        }
      }
    });
  11. Install AutoForm and SimpleSchema

    devel

    To use AutoForm in a Meteor application, you must install the aldeed:autoform package and the simpl-schema NPM package. Additionally, if you intend to use the autoform option within your schemas, you must extend SimpleSchema to recognize this option.

    Note that AutoForm does not include a UI theme by default; you must install a theme package separately (e.g., autoform-bootstrap4).

    $ meteor add aldeed:autoform
    $ npm i --save simpl-schema
    import SimpleSchema from 'simpl-schema';
    SimpleSchema.extendOptions(['autoform']);
  12. Install AutoForm

    devel

    AutoForm is a Meteor package that provides UI components and helpers for creating forms with automatic insert/update events and reactive validation.

    Important Requirements:

    • Versions 6+: You must separately install the simpl-schema NPM package.
    • Themes: Starting with AutoForm 7.0, themes are decoupled. You must install your preferred theme manually.
    • Optional Integration: You can use AutoForm with collection2, but you must add collection2 to your app yourself.