【问题标题】:Populating SELECT options from database in SimpleSchema在 SimpleSchema 中填充数据库中的 SELECT 选项
【发布时间】:2016-09-21 14:14:51
【问题描述】:

在带有 AutoForm + Select2 插件的 Meteor 中使用 SimpleSchema,我正在尝试从数据库中为 Select 字段生成选项。

发布'occupation'集合,并在Meteor中定义一个集合'Occupation'。

在 SimpleSchema 中我有这个:-

occupations: {
    type: [String],
    optional:true,
    label: 'Occupation',
    autoform:{
      type:"select2",
      placeholder: 'Comma spaced list of occupations',
      options: function () {
        Meteor.subscribe('occupations');
        return Occupations.find({});

      }
    }
  }, 

但它不返回收集结果,并在没有错误消息的情况下使应用程序崩溃。

【问题讨论】:

    标签: meteor meteor-autoform select2 simple-schema


    【解决方案1】:

    似乎最好的处理方法是通过帮助程序提供选项列表。

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

    其中listOccupations 是包含表单的模板中的助手。

    Template.myForm.helpers({
      listOccupations: function () {
        Meteor.subscribe('occupations');
        return Occupations.find({}).fetch();
      }
    });
    

    我们从 schena 中移除 options 对象

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

    【讨论】:

      【解决方案2】:

      你试过了吗,这种方法:

      autoform: {
        options: {
          var occupations  = [];
      
          Occupations.find().map(function(occ) {
             occupations.push(
               {label: occ.description, value: occ._id}
             );
          });
      
          return occupations;
        }
      }
      

      希望这会有所帮助..

      【讨论】:

      • 我确实尝试过这样的事情 - 但是异步操作在绘制后没有填充选择。我将使用您的代码进行测试
      【解决方案3】:

      我遇到了同样的问题。我在 /lib/collections 文件夹中定义我的集合模式,它在服务器端和客户端都运行。鉴于此,我拥有的 console.log 在服务器端打印了正确的值,在客户端打印了一个空数组。 我所做的是:

      if (Meteor.isClient){
      Meteor.subscribe('service-categories-list', {
          onReady: function(){
              const serviceCategories = ServiceCategories.find({}).map(function(item, index) { 
                  return {
                      label: item.name, 
                      value: item.slug
                  };
              });
              Schema2._schema.type.autoform.options = serviceCategories;
          }
        })
      }
      

      我知道使用 _schema 不是一个好主意,但我接受建议 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        • 2021-12-24
        • 2014-09-22
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多