Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Call beforeSave() in other model's beforeSave()

Tags:

yii

I am trying to save a record of another model in model's beforeSave() method. I expected the save() method to call the other's model beforeSave(),but it doesn't.Is it a bug or I am just missed something?Here is some code.

Operations model

public function beforeSave(){
    if(parent::beforeSave()){

        if($this->isNewRecord){
            $this->creation_date=$this->modification_date=time();
            $cur=Currencies::model()->find('LOWER(short)=?',array('usd'));
            if($cur->id!=$this->currency_id){
                $conv_cours=Currencies::model()->findByPk($this->currency_id);
                $this->ammount_usd=round(($this->ammount*$conv_cours->buy)/$cur->sell,4);
            }else{
                $this->ammount_usd=$this->ammount;
            }

        }else{
            $this->modification_date=time();
        }

        $opType=OperationType::model()->findByPk($this->operation_type);

        $log=new ActionLogs;
        $log->comment=Yii::app()->user->name.' добавил '.$opType->name;
        /*$log->logtime=time();
        $log->user_id=Yii::app()->user->id;*/
        $v=1;
        $log->save ();

        return true;

    }else{
        return false;

    }

}

And another models beforeSave()

    public function beforeSave(){
if(parent::beforeSave()){
    if($this->isNewRecord){
        $this->logtime=time();
        $this->user_id=Yii::app()->user->id;
    }
    return true;
}else{
    return false;
}

} Thanks.

like image 556
Vit Kos Avatar asked Dec 04 '25 12:12

Vit Kos


1 Answers

The only reason I can think of for Yii not calling beforeSave when you try to save an activerecord is when its validation fails. Either try to do a dump of $object->errors after your save call or try to save it with $object->save(FALSE) to skip validation. Like that we can eliminate this as a cause.

like image 151
Blizz Avatar answered Dec 06 '25 07:12

Blizz