save currency and date value in DB

Hi Guys.

What the best & simple way to save a currency and date value in MySQL?

On my form I have 2 inputs (date and monetaty/currency). I need fill it using Brazilian formmat and save it using DB format.

EDITED

My problem til now is the validate, when fill the form with 1.587,69 it show me an error Value must be a number.

END EDITED

Ex.:

Date (in form): 21/03/2016, Value (in form): 1.587,69

Date (in DB): 2016-03-21, Value (in DB): 1587.69

My config is:

web.php


...

'language' => 'pt-br',

    'components' => [

        'formatter' => [

            'class' => 'yii\i18n\Formatter',

            'dateFormat' => 'php:d/m/Y',

            'datetimeFormat' => 'php:d/m/Y H:i:s',

            'timeFormat' => 'php:H:i:s',

            'decimalSeparator' => ',',

            'thousandSeparator' => '.',

            'currencyCode' => 'R$',

        ],

        /*

         * Antes de inserir os dados no banco, formatá-los para se tornarem compatíveis com determinados tipos de campos.

         */

        'formatterDB' => [

            'class' => 'yii\i18n\Formatter',

            'dateFormat' => 'php:Y-m-d',

            'datetimeFormat' => 'php:Y-m-d H:i:s',

            'timeFormat' => 'php:H:i:s',

            'decimalSeparator' => '.',

        ],

...

index.php


<?= GridView::widget([

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],


            'id',

            'valor:currency',

            'data:date',

            // 'created_at:datetime',

            // 'updated_at:datetime',


            ['class' => 'yii\grid\ActionColumn'],

        ],

    ]); ?>

view.php


<?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'id',

            'valor:currency',

            'data:datetime',

            'created_at:datetime',

            'updated_at:datetime',

        ],

    ]) ?>

I Try use an Behavior class but I can’t understand yet why it doesn’t work.

BaseModel.php


namespace app\models;


use Yii;

use yii\db\ActiveRecord;

use app\components\behaviors\DbAttributesFilterBehavior;


class BaseModel extends ActiveRecord

{

    public function behaviors()

    {

        return [

            'class' => DbAttributesFilterBehavior::className(),

        ];

    }

}



Model that I use to test. TesteModel.php


<?php


namespace app\models;


use Yii;

use app\models\BaseModel;


/**

 * This is the model class for table "teste".

 *

 * @property integer $id

 * @property double $value

 * @property string $data

 */

class Teste extends BaseModel

{

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'teste';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['value'], 'number'],

            [['data'], 'safe'],

            ['data', 'date', 'format' => 'd/M/yyyy'],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'value' => 'Valor',

            'data' => 'Data',

        ];

    }

}



I Think it would be work. I Don’t know what to do anymore.

The correct input for the number is 1587.69 not 1.587,69.

For the comma issue you must adjust the validator NumberValidator::$numberPattern


[['yourAttribute'], 'number', 'numberPattern' => '/* Your custom pattern  */'],

You can also implement a mask input using yii widget.

http://www.yiiframework.com/doc-2.0/yii-widgets-maskedinput.html

For date just use the


Yii::$app->formatter->asDate('your date');

Yes. I know.

My difficulty is it. I need to conver to 1.587,69 from 1587.69. Here in Brazil we use R$ 1.587,69. Users will type using our format.

I tinked that Behavior Class solve these problem.

I think behavior is not the best aproach for this case.

Just use a mask. U can use Kartik Mask Money

http://demos.krajee.com/money

For display the correct currency in a view:

Just use the currency formatter:


echo Yii::$app->formatter->asCurrency($model->salary);

Well… What the purpose of these configuratios:


'components' => [

        'formatter' => [

            'class' => 'yii\i18n\Formatter',

            'dateFormat' => 'php:d/m/Y',

            'datetimeFormat' => 'php:d/m/Y H:i:s',

            'timeFormat' => 'php:H:i:s',

            'decimalSeparator' => ',',

            'thousandSeparator' => '.',

            'currencyCode' => '',

        ],

        /*

         * Antes de inserir os dados no banco, formatá-los para se tornarem compatíveis com determinados tipos de campos.

         */

        'formatterDB' => [

            'class' => 'yii\i18n\Formatter',

            'dateFormat' => 'php:Y-m-d',

            'datetimeFormat' => 'php:Y-m-d H:i:s',

            'timeFormat' => 'php:H:i:s',

            'thousandSeparator' => ',',

        ],

if I need use other class? It’s too hard to me understand it. To me these configurations should resolve this problem. Am I right?

To save the currency value I solve with


[['yourAttribute'], 'number', 'numberPattern' => '/* Your custom pattern  */'],

The regular expression I used was: ^(?:1-9|0)(?:,[\d]{0,2})?$


[['value'], 'number', 'numberPattern' => '/^(?:[1-9](?:[\d]{0,2}(?:\.[\d]{3})*|[\d]+)|0)(?:,[\d]{0,2})?$/'],

Now I try do the same thing with date field.

I try to use on my rules


['data', 'date', 'format' => 'd/M/yyyy'],