Hi there - I want to show a price on a page, minus the percentage sdiscount.
I tried this, which i thought would work, but the output is szero:
[[*percentageDiscount:div=`[[*startingPrice]]`:mpy=`100`]]
Any ideas what I’ve done wrong?
Thanks!
Andy
If you output the TVs directly ( → [[*startingPrice]]
, [[*percentageDiscount]]
), do they have the correct values?
Also, I would write a custom snippet instead of using two output modifiers.
Thanks.
Yes the values output as expected.
Will see if I can write a snippet then although not my strong point!
You can add the TV values as properties to your custom snippet.
For example like this:
[[calculatePrice? &discount=`[[*percentageDiscount]]` &price=`[[*startingPrice]]`]]
Then in the snippet “calculatePrice”, use the variables with the name of the properties:
<?php
return $price - ($price * $discount / 100);
Oh that’s great thank you. I will add this and see if it works asap. Wasn’t expecting you to write it for me. Really appreciate it.
This works really well - and very simple to understand - thanks.
The only issue is that if the product isn’t reduced (so the percentage discount TV is empty, the page throws a 500 error.
I assume in the snippet I need a fallback or something to prevent this?
In the snippet code you could (for example) use this line:
$discount = $modx->getOption('discount', $scriptProperties, 0, true);
It sets the variable $discount
to 0
(third parameter = default value) if the discount
property doesn’t exist or is empty.
Or you could cast the property to a number before it is used in the calculation:
$discount = (float) $discount;
There are also other ways to improve the snippet code:
For example use round() to round the result or number_format() to format it:
$price_with_discount = round($price - ($price * $discount / 100), 2);
return number_format($price_with_discount, 2);
Thank you Harry. I had tried to use output modifiers to determine whether or not to load the new snippet like so:
[[*percentageDiscount:notempty=`[[calculatePrice? &discount=`[[*percentageDiscount]]` &price=`[[*startingPrice]]`]]`]]
But that didn’t work.
I will try your solution within the snippet itself instead.
Thanks
Andy
tm2000:
But that didn’t work.
Nested MODX tags are executed first.
So the snippet “calculatePrice” runs always, no matter if percentageDiscount
is empty or not.
tm2000
May 28, 2024, 7:23pm
10
Ah I see. Thanks for explaining.
system
Closed
May 30, 2024, 7:24pm
11
This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.