How to do some simple math in Meteor's template? - meteor

Let's say I have a simple product_orders collection in Meteor (_id, user_id, user_name, product_name, price_unit, quantity) and I want to show all orders of a single user in table where each row should contain:
user_name, product_name, quantity, price_unit, quantity, price_total (price_unit * quantity)
Additionally I would like to display a grand total for all user's orders.
I don't see easy way to do this in Handlebars.js template as Handlebars doesn't appear to support simple math operations. I can easily return product_order's cursor to my template but don't see easy way to calculate price_total and grand total in template.
I am thinking of creating a template helper of some sort but not sure if that's the proper direction to go. This problem looks like it must have a simple & elegant solution.

Yes, you should write a helper. Handlebars doesn't support using logic in the templates (which is a good practice as it forces you to apply the separation of concerns pattern).
A template helper looks like this:
Handlebars.registerHelper("grandTotal", function(user_name) {
var grandTotal = some_magic_to_calc_total(user_name);
return grandTotal;
});
Then you can call the helper like this from your template:
<template name="foo">
{{grandTotal user_name}}
</template>
You can read more about helpers in the Handlebars.js docs.

Related

is there a way to do a meteor find() based upon more than one field?

Is there a way to do a meteor find (yes, it will be part of a publish function later, i'm just trying to test this)
that is filtered by more than one field at a time?
for example, let's say I only want to return those users who work at Disney in the IT department.
so far I have
Template.managerReports.disney = function () {
return employees.find({'company':"disney"});
};
//for template helper binding to
<template name="managerReports">
{{#each disney}}
<p>{{name}}</p>
{{/each}}
</template>
and attempts to add multiple comma-separated {field:value} pairs results very nicely in these ALSO being found and added to the disney results. I want to reduce results per added field. only data that matches multiple fields gets found.
am I being totally dumb? what is the usual meteor way to deal with multiple conditional finds?
If you want to find users who work for disney AND in the IT department:
employees.find($and: [{company: 'disney'}, {department: 'it'}]);
However, mongodb provides an implicit AND operation when specifying a comma separated list of expressions. So this is more commonly written as:
employees.find({company: 'disney', department: 'it'});
If you want to find users who work for disney OR in the IT department:
employees.find($or: [{company: 'disney'}, {department: 'it'}]);
You need to pass a javascript object, not comma-separated values:
Employees.find({
company: 'disney',
department: 'marketing',
salary: {$gt: 100000},
});

form Entity ordered by translated value

I have an entity category, which has a code. This code is internal, and we use translate it for each language. for exemple, imagine this:
Categories:
---- id:1 Code: "Bread"
---- id:2 Code: "Butter"
I have a form with a form field entity. I want to order it by translated label.
In English for exemple, it will display
Bread
Butter
But in french for exemple, the order is different
Beurre (butter)
Pain (bread)
So I can't use the orderBy of the entity field.
I have a hand-made solution, very dirty: I use an choice field with translated label
$categories_translated =array();
$categories= $this->em->getRepository('MyRepo')->findAll();
foreach($categories as $category){
$categories_translated[$category->getId()]= $this->translator->trans($category);
}
asort($categories_translated);//sorted
//then later
$builder->add('category','choice',array( 'choices' => $choices_technologies) )
Do you have a proper way to do this?
Your way is the best (and I think the only) way to handle this issue with file based translations. There are indeed more possibilities to address problems like this with database related translations. For example: https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/symfony2.md
Are the codes static? i.e. the oven-baked dough (whatever language) is always id=1 in your data dictionaries, then the sorting is fine.
Hypothetically, if you had a table as follows:
category
- catid int auto_increment,
- locale varchar(5),
- itemid int,
- text varchar(100)
One can do select to access to categories sorted by text.
If one just rasterises according to the relevant locale and wanted items, you get global ids for your categories.
You may wish to use a better i18n mechanism, but this would be very simple for static categories.

How to Render Dynamic Choices with Symfony2 + Twig

I'm attempting to dynamically load a select box's options based on some existing criteria in my database. The useful information is that there are 3 classes, a Pet, which has a breed and type, a Breed, which has a name and type, and Type which is something like 'Dog' or 'Cat'.
When editing a pet I have two drop-downs populated from Doctrine/Symfony2.
Type [Select One]
Breed [Select One]
Currently the Breed select lists all breeds of dogs and cats, I'd like to select the 'Type' and have that force the Breed select box to only list Breeds based on that type.
I've done this with raw php/javascript before using Symfony figured there's some best practice for handling it in Symfony.
Any advice would be appreciated. I can provide any additional information needed, but wanted to keep it as simple as possible.
I didnt found any other way than a .change jquery on the first select, then an ajax call with the selected option to repopulate the target select.
$('#Your_source_select').change(function()
{
$.ajax({
type: 'POST',
url: Routing.generate('AJAXDevisOnduleurOptions', { onduleurId: $('#Your_source_select').val() }),
success: function(msg){
$('#Your_target_select').children().remove().end().append(msg);
}
});
});
Please note that Your_source/target_select are entity fields.
But it seems that you got that part.
You might want to use FOSJSRoutingBundle => https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
It allows you to build route in your javascript using twig syntax. So it allows you access to its variables.

How to display the total amount of posts?

What's the best way to display in a block the total amount of posts and comments of my entire drupal website?
thanks
The quick and dirty way:
Ensure that you have PHP filter installed and available to you. Create a block with the php code
<?php
$ncount = db_query("SELECT COUNT(nid) FROM {node} WHERE status=%d", 1);
$ccount = db_query("SELECT COUNT(cid) FROM {comments} WHERE status=%d", 1);
print "Nodes: ".$ncount;
print "Comments: ".$ccount;
?>
One option is to use a View with the block display type. Views Calc can do the summing for you (http://drupal.org/project/views_calc).
Honestly, I think you will find it easier and possibly more performant to create a Statistics content type with CCK integer fields to store the initial values for the amount of each piece of information you need. Then configure the Rules module to increment/decrement the fields when you add or remove content/comments.
A third option I have not personally explored is the Statistics Pro module (http://drupal.org/project/statspro), which says it is Views-compatible.
Use Views GroupBy module ( http://drupal.org/project/views_groupby ). You can specify the filters (e.g. you want to count nodes of particular type only) and so on. It will count the nodes for you.
If your view type is comment then in a similar count can be done on comments.

How do you get a Min() or Max() in drupal using views?

I'm using Drupal's Views 2, and need to retrieve min values from fields in a custom table. The query for this is easy if I were writing it by hand--something like, "SELECT foo, min(bar) FROM table GROUP BY foo." But how would I do this using Views? I've already defined the table in a views.info file, so there's no trouble getting views to see the table. It's the Min() part of the query I just don't understand. My next stop will be the Views API documentation, but if someone can just provide the outline for how to do this quickly, I would greatly appreciate it.
New answer to an old question, but something like this will work. You need to create a custom field handler and then wrap the field as follows:
class views_handler_custom_field extends views_handler_field {
function query() {
$this->ensure_my_table();
$this->field_alias = $this->query->add_field("MAX({$this->table_alias}", "{$this->real_field})",$this->table_alias . "_" . $this->real_field);
}
}
Use aggregation from advanced configuration of views. After this is set
yes you can select max, min or any other selector to fields.
Test your results but it should work well
Alternatively in some cases you can sort your data ascending or
descending and then just pick one to be shown on the view. Can be
problematic when displaying multiple fields or so.
After testing first one seems to be faster at least on small scale.
One could consider the modules groupby and views_calc, but I assume they are not acceptable for you.
Additionally, you can accomplish this with a custom module.

Resources