CActiveRecord::copy

I suggest to add a function to CActiveRecord that creates a copy of that record.

At the moment, I have to write


$new = clone $old;

unset(new->id);

$new->isNewRecord = true;

But this is prone to errors if some internal things of CActiveRecord change.

I think it would be much cleaner if I could write


$new = $old->copy();

(just like in other frameworks, by the way).

The internals of CActiveRecord should not affect the functionality of the code above. You’re using the API (via the setIsNewRecord method, which is used above), which should remain unchanged. CActiveRecord’s implementation of that method may change, but if the API stays the same, your code shouldn’t care how it’s implemented.

Thanks. I did not expect isNewRecord to change, but maybe that a fourth command could be necessary somewhen just to do the simple task of copying an object. And, honestly, I think that creating a copy is such a frequent task that a convenience function is legitimate, even if it only comprises three commands.

Another way of doing this:




$new = new Record;

$new->attributes = $old->attributes;

$new->id = null;



Where "Record" is the name of your model.

This does not depend on the functionality of CActiveRecord, unless Yii would change the behavior of CActiveRecord::getAttributes() and/or CActiveRecord::setAttributes(), which I highly doubt.

Ofcourse you do need to take the scenario and safeAttributes of $old into account when doing this.

i think you can add __clone() function to your model~