Validating and Converting Decimal Values โ€‹โ€‹in CakePHP

I am developing an application with CakePHP that processes monetary values. The client wants the numbers to have a custom format, for example 1.275,34, that is, a dot as a separator in the integer part and a comma as a decimal separator.

I am wondering what is the best approach to managing this, since I need to do two basic things:

  • Confirm the values โ€‹โ€‹recorded in the forms in accordance with this custom format.
  • Convert these values โ€‹โ€‹according to the format expected by the MySQL column data type ( decimal(18,2)in this case, 1275.34in the example above).

I think I have these options, but I'm not completely satisfied, because several models work with this custom format, which means that you are copying some code:

  • Check and convert the value in the controller before the call $this->Model->save(), possibly using the component.
  • Validate data using custom rules in the model (array var $validate) and transform it, possibly using behavior.

What do you recommend? Is there any other approach to this?

Thank!

+3
source share
2 answers

"1.234,56" - , , , . , , setlocale(LC_MONETARY,$locale). , :

setlocale(LC_MONETARY, 'it_IT');

money_format Model::beforeValidate() , . .

+1

PHP number_format() : http://php.net/manual/en/function.number-format.php

, beforeSave() afterFind() , .

http://book.cakephp.org/view/1048/Callback-Methods

, , , , .

virtualFields ( cakePHP 1.3), , . MySQL.

: http://book.cakephp.org/view/1608/Virtual-fields

MySQL: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format

var $virtualFields = array(
    'formatted' => 'FORMAT(12332.1,2)' // would output 12,332.10
);
+2

All Articles