【问题标题】:How do you add values to AutoForm's form object without using a form?如何在不使用表单的情况下向 AutoForm 的表单对象添加值?
【发布时间】:2015-12-27 22:21:56
【问题描述】:

我有一个通过 AutoForm 创建的表单。

就数据来源而言,我可以填写部分表格并使用:

AutoForm.getFormValues('form-id').insertDoc // returns the contents of the form

当我验证表单时,我可以:

var formValues = AutoForm.getFormValues('form-id').insertDoc;

var isValid = MyCollection.simpleSchema().namedContext("myContext").validate(formValues); 

// if isValid returns true, then I enable the Submit button

我想手动将信息添加到 Autoform 用于验证和提交到集合的任何对象中,而不是填写表单的某些部分。

例如,架构中的某些数据字段根本不需要出现在表单本身中。

拿一个购物车:

ShoppingCartSchema = {
  totalPrice: {
    type: Number,
    optional: false
  },
  itemsSelected: {
    type: [Object],
    optional: false
  }
};

itemsSelected 的数据显然是通过用户在表单上输入提供的。

totalPrice 的数据不应该来自表单输入。它是在代码中生成的。

totalPrice 在 AutoForm 将表单提交到集合之前仍需要验证为必填字段。

那么如何将totalPrice 添加到 Autoform 最终验证的对象上?

【问题讨论】:

    标签: meteor meteor-autoform


    【解决方案1】:

    如果您愿意,可以使用自动值。

    ShoppingCartSchema = new SimpleSchema({
      'items': {
        type: [Object],
      },
      'items.$.name': {
        type: String
      },
      'items.$.price': {
        type: Number
      },
      totalPrice: {
        type: Number,
        autoValue: function () {
          if (this.field('items').isSet) {
            let total = this.field('items').value.reduce(function (sum, item) {
              return sum + item.price;
            }, 0);
            if (this.isInsert) {
              return total;
            } else {
              return { $set: total };
            }
          }
        }
      },
    });
    

    【讨论】:

      【解决方案2】:

      Autoform Hooks 可以帮助您在将数据保存到集合之前对其进行操作。

      在你的情况下。

      AutoForm.hooks({
        form-id: { // The Autoform ID
          onSubmit: function (insertDoc, updateDoc, currentDoc) {
            if (customHandler(insertDoc)) { // Your Logic here
              this.done(); // This is Required
            } else {
              this.done(new Error("Submission failed"));
            }
            return false;
          }
        }
      });
      

      更多信息请参考Autoform Readme

      【讨论】:

      • 好吧,在我的情况下,钩子来得太晚了。我有一个Submit 按钮,只有在表单有效时才应该启用它,这意味着totalPrice 值必须存在。但totalPrice 实际上不能作为字段出现在表单上。我可以为totalPrice 创建一个隐藏的表单字段,但我非常 更愿意以另一种方式来做。我有很多其他字段无法显示在表单上,​​但在激活Submit 按钮之前仍需要验证。
      • 如果字段是由代码自动填充的,那么我们可能不需要验证它们(我不知道你的业务需求),因此可以在不检查 totalPrice 的情况下激活提交按钮。或其他隐藏属性
      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      相关资源
      最近更新 更多