Formatting asPercent

I have a table column TaxRate formatted as Decimal 7,5
When Gii creates the model it sets it a Number
Then in my view I use the asPercent( #, 2) and it displays perfectly, but when I try to save it errs. Do I have to switch from Number to String to make this work or am I missing something obvious?

Thank you for your assistance!

Furthermore, I tested and switching to string does appear to work, but then it saves the value incorrectly.

12.25% is saved as 12.25 rather than 0.1225 so then I end up needing to use a beforeSave() in my model to divide the value by 100.

Is this normal? Is this the proper way to handle all of this?

I just get the feeling I’m missing something as Yii always seems very simple and this seems like I’m doing a lot of convoluted manipulations.

Are you using a plugin for inputting this data? If so, what plugin?

Usually the data must be “parsed” right after the user pass it, so you can work in a standard format in the backend, further formatting can be done just before saving to DB or right after recovering from it.

I would recommend you always convert this kind of data, when passed by the user, to numbers. This way you can do computations on the backend without worrying its type.

Here is where the ActiveRecords come into play. If you setup the rules correctly, when you run the validate() method, it will help you a lot.

No, there are not plugins involved at this point.

I simply was trying to use the formatter to make the entry ‘pretty’ -> %12.25 instead of 0.1225. It works to display, but then it seems I have to do a lot of extra coding to parse it before saving. I just wanted to know if this is normal? This also means that since it is now passing %… back the model needs to be switch from number to string.

As far as I know, it is a pain doing this kind of this, and that’s why I use plugins.

Some of the plugins will parse the data on the client-side, sending only the numbers to the backend, where you validate them, saving you this kind of work.

1 Like