0

I have a problem saving the data in the database . It saves them as 1970-01-01 , invalid date . I would read them as dd-mm-yyyy and convert them to the database in yyyy-mm-dd .

my model

public function behaviors()
{
    return [
        [
            'class' => AttributeBehavior::className(),
            'attributes' => [
                attribute ['created','updated']
                ActiveRecord::EVENT_BEFORE_INSERT => ['data_arrivo','data_part'],
                ActiveRecord::EVENT_BEFORE_UPDATE => 'data_arrivo', 'data_part'
            ],
            'value' => function ($event) {
                return date('Y-m-d', strtotime($this->data_part));
            },
        ],
    ];

Any suggestions?

Saba
  • 115
  • 1
  • 15

1 Answers1

1

You can use beforeSave event in model file. It will get call before saving the record into the table.

 public function beforeSave($insert) {
    if($this->data_part){
      $this->data_part = Yii::$app->formatter->asDate(strtotime($this->data_part), "php:Y-m-d");
    }
    return parent::beforeSave($insert);
  }

Don't work i post my code

 public function beforeSave($insert) {
    if($this->data_part){
      
 $this->data_part = Yii::$app->formatter->asDatetime(strtotime($this->data_part), "php:Y-m-d");
    
    if($this->data_arrivo)
        $this->data_arrivo = Yii::$app->formatter->asDatetime(strtotime($this->data_arrivo), "php:Y-m-d");
    
  }
  return parent::beforeSave($insert);
}
Saba
  • 115
  • 1
  • 15
Manikandan S
  • 902
  • 1
  • 8
  • 18
  • This function is to implement with behaviors ( ) ? – Saba Sep 19 '16 at 13:58
  • No. It's a active record event method. It will work similar like behaviors. For your reference - http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#beforeSave()-detail – Manikandan S Sep 19 '16 at 14:01
  • I can not make it work , maybe because I have 2 parameters for the date ? data_part , data_arrivo – Saba Sep 19 '16 at 14:47
  • Yes, inside the beforeSave method, you can add another if condition for 'data_arrivo' variable. – Manikandan S Sep 19 '16 at 14:52