【问题标题】:How to populate autoForm select with values from collection in Meteor?如何使用 Meteor 中集合中的值填充 autoForm 选择?
【发布时间】:2016-01-30 21:23:48
【问题描述】:

我刚刚为 Meteor 找到了这个很棒的 autoForm 包,我想将它与 select2 一起使用。

我的目标是使用 autoForm 轻松地为我的收藏创​​建一个输入表单。障碍是:如何使用另一个集合中的字段填充它以及如何使其多选?

在我的 lib/collections 中,我声明了一个 Meteor 集合:

Clients = new Mongo.Collection('clients');
Clients.attachSchema(new SimpleSchema({
    clientName: {
        type: String,
        label: "Mandator Name",
        max: 200
    }
}));

现在我没有得到关于 autoForm 的文档。在大气页面(https://atmospherejs.com/aldeed/autoform)上,如果我没记错的话,我应该使用这样的东西:

{{#autoForm collection="Clients" id="insertClientForm" type="insert"}}
    {{> afFieldInput name="clientName" options=options}}
{{/autoForm}}

然后像这样写一些JS:

Template.registerHelper({
    options: function() {
        return Clients.find({}, {fields: {clientName: 1}});
    }
});

模板渲染得很好,我可以看到一个输入框。但是它不是多选,它根本不允许我选择任何值。

关于问题出在哪里的任何想法?

额外问题:如何在 autoForm 生成的选择输入上使用 select2? 编辑:使用 aldeed:autoform-select2 来使用 select2。

【问题讨论】:

  • 刚刚自己解决了奖金问题。还有另一个名为 aldeed:autoform-select2 的包可以解决问题。

标签: javascript meteor meteor-autoform meteor-collection2 simple-schema


【解决方案1】:

您需要将您的集合映射到一个标签和一个值; label 是客户端将看到的内容,value 是提交时将保存的内容。

https://github.com/aldeed/meteor-autoform#use-a-helper

Template.registerHelper({
    options: function() {
        return Clients.find({}, {fields: {clientName: 1}}).map(function (c){
      return {label: c.clientName, value: c._id};;
    }
});

如果您想要多选,您需要将架构键类型设为[String] 而不是String

【讨论】:

  • 这不起作用。但是我将它直接映射到架构并且有效。现在在填充的 select2 autoForms 上运行。
【解决方案2】:

我已经使用 Meteor 测试了这个解决方案

aldeed:collection2 aldeed:autoform natestrauser:select2 aldeed:autoform-select2

假设您有一个包含用户个人资料信息的表单,其中一个字段是“职业”(如他们的工作等),并且您希望他们从列表中选择一个职业。

1) 发布要用于选择选项的集合。

在服务器上

Meteor.publish('occupations', function () {
  return Occupations.find();
});

2) 在客户端订阅集合

在客户端

Meteor.subscribe('occupations');

3) 为表单模板创建一个助手

Template.CreateUser.helpers({
  listOccupations: function () {
    return Occupations.find({}).fetch();
  },
});

4) 最后在 autoForm 字段的 options 参数中引用该助手 - 在这种情况下,我使用了 afQuickField

{{> afQuickField name='occupations' multiple=true tags=true options=listOccupations}}

5) 并确保您的架构设置正确以使用 Select2

occupations: {
    type: [String],
    optional:true,
    label: 'Occupation',
    autoform:{
      type:"select2",
      placeholder: 'Comma spaced list of occupations',
    }
  },

【讨论】:

  • 我无法再测试这个,因为我无法再访问代码了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2023-03-23
  • 2013-01-12
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多