2016-04-23 9 views
0

adminsでは、の新しいタグの「ニュースとイベント」エントリにタグを付けることができます。これは正常に動作してNewsEvents内の文書は、次のようになりますSelectize.js:データベースから入力フィールド(Meteor&MongoDB/JSON)に既に選択されているタグをプリロードする方法

{ 
    "_id" : "nbMJdwjkDjZ4twkvi", 
    "keywords" : [ 
     "math", 
     "analysis", 
     "beginner" 
    ], 
    "title" : "brand new article for analysis beginners", 
    "description" : "testing here the tagging system", 
    "type" : "news", 
    "createdAt" : "Thu, 21 Apr 2016 04:53:21", 
    "publishedAt" : "Thu, 21 Apr 2016 04:53:21", 
    "modifiedAt" : "Thu, 21 Apr 2016 04:54:15" 
} 

タグがTagsと呼ばれる別のコレクションに保存されます。例:

{ 
    "_id" : "P4XoEtsogwhDvNNTv", 
    "name" : "math" 
} 

問題:管理者は、編集/数日後にタグを追加したいです。選択したタグをデータベースから事前に抽出することはどのように可能ですか?

Template.adminNewsEventsEdit.onRendered(function() { 
    ... 
    // Get an array of the existing tags 
    var tagOptions = Tags.find().fetch(); 

    $('#newsKeywords').selectize({ 
     plugins: ['remove_button'], 
     delimiter: ',', 
     persist: false, 
     valueField: 'name', 
     labelField: 'name', 
     searchField: 'name', 
     create: true, 
     highlight: true, 
     maxOptions: 5, 
     options: tagOptions, 
     onItemAdd: function (item) { 
      // Check to see if tag exists in Tags collection 
      // by querying the database for the tag name 
      // and checking the length of the result 
      var existingTag = Tags.find({"name": item}).fetch().length; 
      if (!existingTag) { 
       // Add the tag to the Tags collection 
       Tags.insert({"name": item}); 
      } 
     } 
    }); 
}); 

答えて

0

私はあなたがAPI関数addItem(see here)

例えばを使用したいと思う:

これはnews-events-edit.jsのための私のヘルパーです

Template.adminNewsEventsEdit.onRendered(function() { 
    ... 

    // Get an array of the existing tags 
    var tagOptions = Tags.find().fetch(); 

    // Set up selectize 
    var selectize = $('#newsKeywords').selectize({ 
     plugins: ['remove_button'], 
     ... 
    }); 

    // Get the keywords on this news entry 
    var keywords = this.data.keywords; 

    // Add each keyword to the selectize. 
    _.each(keywords, function(word) { 
     // To do this we use the tag _id of each keyword 
     var tag = _.find(tagOptions, function(opt){ 
      return opt.name === word; 
     }); 

     selectize.addItem(tag._id, true); 
    } 
}); 
+0

ご協力ありがとうございます。私はaddItemを使って作業することを考えましたが、どうやって理解できませんでした。とにかく、あなたの答えは以前に選択されたタグで入力フィールドをあらかじめ入力していませんでした:(btw:_.each関数の閉じ括弧が必要です。 –

関連する問題