I have schema similar to this:
Schema.Adviser = new SimpleSchema({
"firstName": {
type: String
}
});
Schema.Orders = new SimpleSchema({
"adviserId": {
type: Object
},
"period": {
type: Date
},
"order": {
type: Number,
min: 0
}
});
I need to render a table like this:
first name | January | February
Bob | 1 | 0
Bill | 0 | 1
Each value is an input field that is editable.
If for example there is no order record for Bob in January I need January to still render, ideally with a 0 such that someone can add a January order.
Something like this:
months is an array of months to be shown. Each follows the format: Mon Feb 01 2016 00:00:00 GMT+0000
{{#each month in months}}
{{#each getOrders}}
{{#if equals month period}}{{order}}{{/else}}0{{/if}}
{{/each}}
{{/each}}
Not only can I not get this to work, but before spending much more time trying to debug the issue I'm wondering if this is really the best way to do this.
Any advice?
Many thanks
var months = ['Jan', 'Feb', 'Mar'];
var advisors = [{
ID: 1,
name: 'Bob'
}];
var emptyMonthArray = [0, 0, 0];
orders = [{
advisorID: 1,
period: new Date(),
order: 3
}];
function getAdvisors() {
var returnArray = [];
advisors.forEach(function(a) {
var returnObject = {
name: a.name,
monthData: emptyMonthArray.slice(0)
};
orders.forEach(function(o, i) {
if (o.advisorID === a.ID) {
returnObject.monthData[o.period.getMonth()] = o.order;
}
});
returnArray.push(returnObject);
});
return returnArray;
}
console.log(getAdvisors());
I think a bit cleaner way of doing this is to make a getAdvisors helper that would process and transform the data and return something like
[
{name:'Bill', monthData:[0,1,0,2,...]},
{name: 'Bob', monthData:[...]}
]
which much neater could be expressed in a Template something like this:
<tr>
<th>Name</th>
{{#each month in months}}
<th> {{monthname}}</th>
{{end each}}
</tr>
{{#each advisor in getAdvisors }}
<tr>
<td>{{name}}</td>
{{#each monthData in advisor}}
{{td>{{this}}</td>
{{end each}}
</tr>
{{end each}}
EDIT: added a fiddle https://jsfiddle.net/runjep/1xrp1gfq/ (this will only work the first 3 months of the year ;-) after that you would have to add 'Apr',...
EDIT again using your fiddle https://jsfiddle.net/runjep/0qy34pfe/3/
Unfortunately meteorpad is down so here's what I think will work.
{{#each advisers}}
{{firstName}}
{{#each monthData}}
{{this}}
{{/each}}
{{/each}}
Related
I have a table with the Aurelia structure as follows:
//app.ts
products = [{
name: "book",
options: [{
prop1: value1,
prop2: value2
}, {
prop1: value1,
prop2: value2
}, {
prop1: value1,
prop2: value2
}]
}, {
name: "notebook",
options: [{
prop1: value1,
prop2: value2
}, {
prop1: value1,
prop2: value2
}, {
prop1: value1,
prop2: value2
}]
}, {..and so on}];
selectProduct(product) {
this.selectedProduct = product;
}
saveOption(option) {
// save the edited option value in the database
}
// app.html
<tr repeat.for="product of products">
<td click.trigger="selectProduct(product)">${product.name}<td>
<td repeat.for="option of product.options">
<input type="text" value.bind="option.prop2" blur.trigger="saveOption(option)">
</td>
</tr>
Here's what the actual table in my original app looks like, the above code is a simplified version of the table. table
Basically, I want to enable the user to be able to do following:
edit any cell in any row, and on cell blur, it saves the edited value in the database.
click on the first column of any row, which is the product name, to select and highlight that particular row.
It works fine, except for the following use case:
User edits a cell in any row, and immediately clicks on the first column name (any row, not necessarily the edited row).
Ideally, it is supposed to save the edited value and select that particular row(the row whose name was clicked after editing, not necessarily the edited row) at the same time. (blur triggering the saveOption(option) and clicking on name triggering the selectProduct(product)).
But what is happening is, it triggers saveOption(option) on blur, but does not trigger selectProduct(product), somehow the blur event is preventing the click event.
Am I missing something, or is there a cleaner way to achieve two event calls simultaneously? Thanks.
You could pass the product to the saveOption method, and call selectProduct at the end of saveOption
selectProduct(product) {
this.selectedProduct = product;
}
saveOption(option, product) {
// save the edited option value in the database
this.selectProduct(product);
}
<tr repeat.for="product of products">
<td click.trigger="selectProduct(product)">${product.name}<td>
<td repeat.for="option of product.options">
<input type="text" value.bind="option.prop2" blur.trigger="saveOption(option, product)">
</td>
</tr>
I have a collection with this item:
{
"item1": ["foo", "bar", "baz"],
"item2": ...
}
I made a helper function to repeat a template for each item in item1
Template.temp.helpers({
items: function() {
return Col.find({},{item1:1});
}
});
and this is the template
<template name="temp">
{{#each items}}
{{> anotherTemplate}}
{{/each}}
</template>
But I get back an empty array. Why doesn't it work?
Try with {{#each items.item1}}
Because, Col.find({},{item1:1}) just remove all other field from result.
Limit Fields to Return from a Query
It's like SELECT item1 FROM table in SQL
If you need repeat your template for each item in item1, you need to precise which array should be use.
<template name="temp">
{{#each items.item1}}
{{> anotherTemplate}}
{{/each}}
</template>
Meteor mongo methods are a little different you cannot use.
return Col.find({},{item1:1});
you can use it this way:
return Col.find({},{fields:{'item1':1}});
Maybe you want:
{{#each items}}
{{#each item1}}
{{> anotherTemplate}}
{{/each}}
{{/each}}
Or this:
Template.temp.helpers({
items: function() {
return Col.find({},{item1:1}).map(function(item){
return item.item1
})
}
});
That way items will return the item1 array. Originally it was returning an array of objects with just one element, the item1 arrays of each object:
[{
item1: ["foo","bar","baz"]
},
{
item1: ["lah","nah","jah"]
},
{
item1: ["see","gee","bee"]
}]
this way you'll get an array of arrays: [["foo","bar","baz"], ["lah","nah","jah"], ["see","gee","bee"]]
I think you need to do return something like this from helper
return Col.findOne({}).item1
It should work now
Thanks
In mongodb i have json values like and it is not fixed. Some time it will be only 2 or 3 and sometime it will be very large.
{"_id" : "p83oZAo7fdhNuDD34",
"Active Template Name" : "Windows Mobile",
"ProductId" : "456",
"Subcategory" : "on",
"Size" : "on",
"Material" : "A",
"Price" : "2345",
"Combo Id" : "67u",
"Color" : "red",
"Status" : "Pending"
},
{
"_id" : "p83oZAo7fdhNuDD34",
"Material" : "A",
"Price" : "2345",
"Combo Id" : "67u",
"Color" : "red",
"Status" : "Pending"
}
I want to show all keys like (id, Active Template Name, ProductID .......) as table header and values (p83oZAo7fdhNuDD34,Windows Mobile,456 .......) in tbody.
I am not getting the exact way to perform this in meteor. My collection name is products and Html code is bellow.
<template name="productvalue">
<table>
</table>
</template>
Use a {{#each}} block helper to iterate over your collection products.
<template name="productvalue">
<table>
<thead>
<th>Id</th>
<th>Active Template Name</th>
<th>ProductId</th>
[...]
</thead>
<tbody>
{{#each products}}
<tr>
<td>{{_id}}</td>
<td>{{activeTemplateName}}</td>
<td>{{ProductId}}</td>
[...]
</tr>
{{/each}}
</tbody>
</table>
</template>
You also need to define helpers to rename the problematic keys containing invalid Spacebars characters.
Template.productvalue.helpers({
products: function(){
return Products.find();
},
activeTemplateName: function(){
return this["Active Template Name"];
},
[...]
});
If you want to display a table with all the possible properties in the header, and each row with each column filled or not whether the property is defined or not for the document in that row, then you will need to:
Ahead of time (in onCreated or onRendered), find all possible properties for your dataset, order them, and store them in a "header" object accessible to your helpers. (either in Session or using a reactive variable) Make it reactive if necessary, using this.autorun().
Then, do the same as above, except just returning the stored ordered list for tableHeader
And for rowContent, iterate over your stored header and fill an array with empty strings for each undefined field in the current document
Example:
function getHeader(products) {
var header = {};
for (var key in products) {
for (var property in products[key]) {
header[property] = true;
}
}
return Object.keys(header);
}
Template.productvalue.onRendered(function () {
var products = Products.find().fetch();
Session.set('header', getHeader(products));
this.autorun(function () {
var products = Products.find().fetch();
Session.set('header', getHeader(products));
});
});
Template.productvalue.helpers({
'tableHeader': function () {
return Session.get('header');
},
'rowContent': function (document) {
var row = [];
var header = Session.get('header');
for (var key in header) {
row.push(document[header[key]] || "");
}
return row;
}
});
And in template:
<template name="productvalue">
<table>
<thead>
{{#each tableHeader}}
<th>{{this}}</th>
{{/each}}
</thead>
<tbody>
{{#each products}}
<tr>
{{#each rowContent this}}
<td>{{this}}</td>
{{/each}}
</tr>
{{/each}}
</tbody>
</table>
</template>
I still recommend using a reactive variable instead of Session, but the demonstration is complicated enough as it is.
My collection has documents with card as a subdocument array holding each card. Each card is an object with many keys. The two keys for expiration are expiration_month and expiration_year.
Here is an example.
{
_id: '1',
card: [
{
'expiration_month': 10,
'expiration_year': 2017
},
{
'expiration_month': 01,
'expiration_year': 2015
},
]
}
How would I publish the right list to the subscription for this route so that I can use an each loop to get the right list? I just want to get any cards that expire in the next three months.
{{#each expiring_cards}}
{{> ExpiringCards}}
{{/each}}
Meteor.publish('card_expiring', function () {
var before_date = moment(new Date()).add(3, 'month');
return Donate.find( { moment(new Date('card[0].expiration_year' + '/' + 'card[0].expiration_month'))._d : { $lte: before_date} });
});
I know the above code for publish doesn't work, how could I change it to make it work, or is there a better way to do this?
Thanks
Easiest way seems to be to join these two fields into a Date object, then run the below query.
How to combine the two fields - answer here
Meteor.publish('card_expiring', function () {
var today = new Date();
var future_date = new Date(new Date(today).setMonth(today.getMonth()+3));
return Donate.find({'card.expires' : {$lte : future_date }}, { card : true } );
});
Of course this just gets me any card subdocument that matches this query, which means that would include the cards that don't match, but that are in a subdocument that does.
To filter even further I used this in my helper.
Template.ListExpiringCards.helpers({
list: function () {
//The subscription filters out the records with subdocument card,
//which contain cards expiring in the next 3 months
return Donate.find();
},
expiring_cards: function () {
//This further filters only to the cards that match the above criteria
// then returns an array to the Meteor template for the each loop
var returnThisValue = [];
this.card.forEach(function(entry) {
var today = new Date();
var future_date = new Date(new Date(today).setMonth(today.getMonth()+3));
if (entry.expires <= future_date) {
returnThisValue.push(entry);
}
});
return returnThisValue;
}
});
And this in my template
{{#each list}}
{{#each expiring_cards}}
{{> ExpiringCards}}
{{/each}}
{{/each}}
Alright, so I'm making a recursive list in AngularJS using ng-include and ng-repeat, something like this:
<div id="wrapper">
<div id="text" ng-click="DivClick()">
<ul>
<li id="{{$index}}" ng-repeat="data in layer" ng-include="'recursion.html'"></li>
</ul>
</div>
<script type="text/ng-template" id="recursion.html">
<textarea myd-keypress cols="63" rows="1">{{data.content}}</textarea>
<input type="text" myd-numbers value="{{data.price}}"></input>
<ul>
<li ng-repeat="data in data.layer" ng-include="'recursion.html'" id="{{$parent.$attr('id') + '-' + $index}}"></li>
</ul>
But of course, it doesn't work. So basically what I need is that every < li> element in dom has id that corresponds like this:
0
1
1-0
1-1
1-1-0
1-2
1-3
2
2-0
so that every new < li> has id that equals "id of its parent" + "-$index".
What I know that will work is that scope.layer[] and its layer descendants contain a field that will save ID of the < li> and display it, but I want to avoid saving that extra field in the DB because solution to this is really simple (as shown in the example), but I can't get over syntax. Any suggestions?
Before passing data to $scope.label you could loop over it with function that recursively loops branches and adds an id property
var data = [{
name: 'foo',
children: [{
name: 'foo child',
children: [{
name: 'foo child grandchild'
}, {
name: 'foo child grandchild2'
}]
}, {
name: 'foo child2'
}]
}, {
name: 'bar'
}]
function createID(arr, parentID) {
for (var i = 0; i < arr.length; i++) {
var id = (i + 1).toString();
var thisID = parentID ? parentID + '-' + id : id;
arr[i].id = thisID;
if (arr[i].children) {
createID(arr[i].children, thisID)
}
}
}
createID(data, null)
DEMO http://jsfiddle.net/z4RPz/
What I think you're wanting to do is reach up and grab the $index from the parent element.
You can do that using $parent.$index - or in this case, it may be $parent.$parent.$index, as you're using ng-repeat -> ng-include -> ng-repeat
See this answer for more information on a similar situation:
https://stackoverflow.com/a/15257501/317180