Yii2: Format decimal values in an activeForm field

Created on 13 May 2015  ·  23Comments  ·  Source: yiisoft/yii2

As far as I can see there are basicly two ways to format a decimal value for activeForm fields.

First one is to create getter und setter functions to prepare and return a formatted value. Here you can use the php NumberFormatter class which will use the language depended decimal sign and group separator. This way you need to write these functions for each decimal field (or one magic method) .

The second way is using the maskedInput widget. Here you need to define the groupSeparator and radixPoint manually. I propose to set the default values for those fields within the widget based on the language.

A third option could be implemented similar to the widget function of the activeField class. You might allow using the formatter class or any other function which formats the output string.

enhancement

Most helpful comment

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

п.с. ну и извращенец вы батенька

All 23 comments

Yii::$app->formatter->asDecimal

@lynicidn, that's the way to format decimals in normal views. But I don't see how to use this in combination with activeForm fields?

 <?= $form->field($model, 'ablesewert') ?>

Did I missed something?

Field should set value w/o prepare

or u can set value in manual mode

@lynicidn, the field need to be prepared. Decimal comma is an absolute requirement (in some countries). Beside that I don't know how to set value in manual mode. Or do you mean without active field widget? Can you pls. give an example?

In general I would expect some assistance from a framework or at least a clear documentation how to handle decimal values.

I already raised this question in the forum but got no response. All I found so far are some articles based on yii version 1. But nowhere an descripiton how to handle the whole process from reading a decimal value, render it (localized by country), check the rules and save the new value.

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

п.с. ну и извращенец вы батенька

Hi, I'm new to Yii2, have the same Problem and did it this way:
In model, i change the format bevor use:

    $this->Preis = yii::$app->formatter->asDecimal($this->Preis,2);

To write back, the input-value will be transformed by filter rule:

    ['Preis', 'filter', 'filter' => function ($value) {$value = str_replace(',', '.', $value); return $value; }],

It's not elegant and you have to do it in each model for each decimal, but it works.
Comments?

we could add a format property to ActiveField like we have it in the gridview columns.

... that would be great! It seems to be more like "dataFormat" or similar, because it should be adjustable for both directions.

@cebe I could try to make a PR

@freezy-sk you're welcome.

@cebe better add setter and getter prioritet upper that getAttribute and setAttribute =)

@lynicidn AR should not be responsible for the presentation layer, you may want to get human readable format but also machine readable format for one attribute dependend on the context. thats why getters and setter are not good in this case.

@cebe i understand, in core need replace all $this->$name to $this->getAttribute($name) :(

what? why?

@cebe
in rest model i can prepare value - fields
in base model too - getter and setter and remove public $attribute property from model
in ar model it's not real.

Why i cant find this changes and ability to use format option for textinput fields in 2.0.8 version?

@conick because that PR #9208 is still not merged

@cebe why we need format value for text input and area, it will not validated in request, if it validated, than ur model instantiated as not valid.

The idea make no sense to me: after number is formatted according to the specific locale (including thousands and decimal separators) it usually becomes unparsable and will no longer recognized as number by JavaScript or PHP.

For example: both for PHP and JavaScript following value is a valid number: 1500200.56. However after being formatted it becomes following: 1 500 200,56. Now nethier JavaScript nor PHP is unable to parse this string and extact actual number value from it, unless a specific parser created.

Allowing formatter on text input values will break existing ActiveForm client-side validation as well as regular server-side validation.

If you want a text input value been formatted in a specific way like locale-aware decimal number, you should use maskedinput jQuery plugin or similar solution.

это бред чистой воды уже, формат это от форматера методы asX , там не только преобразование числовых типов, там есть и asHtml и прочая ненужная фигня.
Если аттрибут модели увас содержит некорректное значение, которое надо преобразовать, то почему вы это делаете в виджете ActiveField, чтобы вы не крутили, придет строка и запишется в валуе строка. Ваша "надуманная проблема" решается куда проще

class MyModel extends Model
{
    public function attributes()
    {
        return ['value'];
    }
    private $_value;
    public function setValue($value)
    {
        $this->_value = $value;
    }

    public function getValue()
    {
        return Yii::$app->formatter->asHtml($this->_value)
    }
}

Won't be implemented in 2.0.

Was this page helpful?
0 / 5 - 0 ratings