1

Maybe I'm overlooking something, but can't find a solution on the interwebs..

I have 2 (money) fields: product.price and product.oldPrice

When I try to calculate the discount like this (I'm aware that this simple approach shouldn't work):

{% set discount = product.price / product.oldPrice * 100 %}

I get this error message: Unsupported operand types: Money\Money / Money\Money

And when I try calling it as a 'float':

{% set discount = product.price|number_format(2) / product.oldPrice|number_format(2) * 100 %} 

I get this error message: Object of class Money\Money could not be converted to float

The only solution I can think of is changing the field type in 'Float', but that would make things more difficult.

I also tried Martin Spains solution, who suggested to call the value of the objects like this:

{% set discount = product.price.value / product.oldPrice.value * 100 %}

But then I get this error:

Neither the property "value" nor one of the methods "value()", "getvalue()"/"isvalue()"/"hasvalue()" or "__call()" exist and have public access in class "Money\Money".

I hope someone has a solution for me

2
  • 2
    I've not used Money fields before, but I wonder if you might need to access the value of the field like this: product.price.value to get the value itself rather than the field model. Commented Feb 15, 2023 at 14:42
  • Thanks @MartinSpain! I gave it a try, but unfortunately without any luck. Check my updated post
    – Hielke
    Commented Mar 7, 2023 at 9:41

1 Answer 1

2

As always, for anything non-trivial, you're probably better off writing a Twig extension to abstract your logic to PHP...

That said, for "quick and dirty" calculations, Money objects have an amount property that will give you the value (but as a string, and in cents). It's pretty easy to parse that to something more useful though:

{# get the value of a money field as a float #}
{% set value = moneyField.amount | float / 100 %}

You can then do whatever math operations you need to do, before piping through the currency filter for formatting:

{{ value | currency('USD') }}

You can also use the Money object's currency property if you need to dynamically determine the currency from the field:

{{ value | currency(moneyField.currency) }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.