Yii2: How to format input number to currency es-AR?

2.1k Views Asked by At

I have a _form.php file with this field:

<?= 
$form->field($model, 'price')
->textInput([
    'class' => 'form-control',
    'type' => 'number'
])
?>

The price has this format 1234.50. I would like to have the format es-AR, like this: 1234,50.

In the GridView of index.php I use this code and it works great so I would like to do the same in the _form but it is not working.

[
    'attribute' => 'price',
    'value' => function($myModel) {
        $myFormat = new NumberFormatter("es-AR", NumberFormatter::CURRENCY);
        return  $myFormat->formatCurrency($myModel->price, "ARS");
    },
]
2

There are 2 best solutions below

0
On

There are 2 ways to do that:

  • Add extra class to the price field and use javascript to convert to format you want (remember to return it back on submit)
  • Create priceFormat() and use it on AfterFind event and remember to use priceUnFormat() to return to decimal on BeforeSave
1
On

Use:

$form->field($model, 'attr', ['inputOptions' => ['value' => Yii::$app->formatter->asDecimal($model->attr)]])