Issue
i'm currently working on a quotation module for my Prestashop 1.7.5. I've added prices for products (by overriding Product.php).
And now, I've to make some calculations when a quotation is generated/displayed to add these prices to total of products and order total.
By a simple foreach in the template, i have all my prices.
{foreach $products as $product}
{$product.service}
{/foreach}
OUTPUT
0,30 € 0,10 € 0,20 €
But, I want these numbers to add themselves each to others (e.g here for a total of 0,60€).
By the way, I know we should do that in php files and not in template (i tried this way too, but very complicated...). And, I don't need to save these numbers it's just for the display...
Any ideas ?
Thanks ;)
Solution
The following will handle it. In the first block I simulate your data, than I run the exactly same foreach
from your question, to compare the output.
Finally, in the third block, I show you the code to calculate the total, and also format the output as money.
{* Sample code to simulate your data *}
{assign var="products" value=[
['service' => '0,30 €'],
['service' => '0,10 €'],
['service' => '0,20 €']
]}
{* Original code, exactly as showed in the question *}
{foreach $products as $product}
{$product.service}
{/foreach}
{* This is the new code for calculating the total *}
{assign var="total" value=0}
{foreach $products as $product}
{assign var="total" value=$total + $product.service|replace:' €':''|replace:',':'.'}
{/foreach}
Total: {$total|number_format:2:",":''} €
Output:
0,30 € 0,10 € 0,20 € Total: 0,60 €
But as you are already aware, this is very hacky, and should typically not be handled inside the template, for the following reasons:
- It's very fragile to do string substitutions like the above to remove the euro sign from the
service
attribute. - You should not create new variables inside the template. They should be calculated inside your business rule class.
Typically, you should do the sum before adding the euro sign to your string, because it is always fragile to parse a string back to a number. Even a small change that you make in the future in the service
property (like storing it as '€0,30' instead of '0,30 €' , is enough to break the summation logic.
Answered By - pagliuca Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.