Ability For Beforesave() To Convert Insert Into Update

Ability for beforeSave() to convert INSERT into UPDATE.

In many to many relationship, there is often a need to just reuse an existing record on save.

In Yii 1.14 I can do something like this.




    protected function beforeSave() {

	$duplicate = $this->findByAttributes(array('symbol' => $this->stock_symbol));

	if ($this->isNewRecord && $duplicate !== NULL) {

	    $this->id = $duplicate->id;

	    $this->isNewRecord = FALSE;

	}


	if ($this->isNewRecord === FALSE) {

	    return false;

	}


	return parent::beforeSave();

    }



The problem is save() method will return false, making it look like save has failed.

The workaround is to also overload beforeValidate() but this method is not called when saving without validation.




    protected function beforeValidate() {

	if ($this->isNewRecord) {

	    $duplicate = $this->findByAttributes(array('symbol' => $this->stock_symbol)));

	    if (isset($duplicate)) {

		$this->id = $duplicate->id;

		$this->setIsNewRecord(false);

	    }

	}

	return parent::beforeValidate();

    }



This is a guess based on my Yii V1 knowledge…

Switching $this->scenario from insert to update …

if( $condition )

$this->scenario = update; ** edited made a mistake.

Worked for me before. You may also need to set isNewRecord to false so your code doesn’t get confused;

( P.S I also think this could be done a lot better, if you’ve changes attributes this could get way too confusing to debug. Seems like it is designed poorly if you are saving without validators to begin with )