Search code examples
javascriptmeteormeteor-autoform

AutoForm fields


I am creating a form by using the package aldeed:autoform

So this how my code is

CompanyData = new Mongo.Collection('companyData');
CompanyData.attachSchema(new SimpleSchema({
    allFields: {
        type: String,
        allowedValues: ['title', 'logo', 'url'],
        autoform: {
            type: "selectize"
        }
    },
    title:{
        type:'String',
        label:'Name',
        unique:true,
        max:100
    },

    logo:{
        type:'String',
        label:'Logo',
        optional:true
    }
}));

This is what I need

  1. When the user inserts the data in a collection, I want to add a field called 'createdBy' whose value will be userId.

  2. When a user updates the data, I want to add a field called 'updatedBy' whose value will be userId.

Now 'createdBy' field should not get updated when user updates the data. But the 'updatedBy' field should be updated.

And yes, when the form fields are shown, createdBy and updatedBy fields are to be NOT shown.

Any help


Solution

  • There is clear documentation for this on the meteor-collection2 readme (https://github.com/aldeed/meteor-collection2#autovalue).

     // Force value to be current date (on server) upon insert
      // and prevent updates thereafter.
      createdAt: {
        type: Date,
        autoValue: function() {
          if (this.isInsert) {
            return new Date;
          } else if (this.isUpsert) {
            return {$setOnInsert: new Date};
          } else {
            this.unset();
          }
        }
      },
      // Force value to be current date (on server) upon update
      // and don't allow it to be set upon insert.
      updatedAt: {
        type: Date,
        autoValue: function() {
          if (this.isUpdate) {
            return new Date();
          }
        },
        denyInsert: true,
        optional: true
      }
    

    In this example from the documentation, createdAt and updatedAt are used. You simply need to change these to reference the user ID.

      createdBy: {
        type: String,
        autoValue: function() {
          if (this.isInsert) {
            return this.userId;
          } else if (this.isUpsert) {
            return {$setOnInsert: this.userId};
          } else {
            this.unset();
          }
        }
      },
      updatedBy: {
        type: String,
        autoValue: function() {
          if (this.isUpdate) {
            return this.userId;
          }
        },
        denyInsert: true,
        optional: true
      }
    

    You can add this to each field to prevent it from showing up in autoforms/quickforms:

    autoform: {
      omit: true
    }
    

    Or you can use omitFields="createdBy,updatedBy" in your forms.