I'm new to yii. I collect data from a form using a model extended by CFormModel
and inside controller I want to copy these data to a model which is extended from CActiveRecord
in order to save to DB. Is there a method or way to copy data from data collected model to data saving model rather than doing this by attribute to attribute as it's so ugly. Thanks in advance.
you can get all models attributes by:
$data = $model->attributes;
and assign them to another model
$anotherModel = new AnotherActiveRecord();
$anotherModel->setAttributes($data);
$anotherModel->save();
now another model will extract whatever it can from $data
You can use the following method
public function cloneModel($className,$model) {
$attributes = $model->attributes;
$newObj = new $className;
foreach($attributes as $attribute => $val) {
$newObj->{$attribute} = $val;
}
return $newObj;
}
Define this in dome component , say UtilityComponent. Then you can call as
$modelTemp = $new ModelClass();
$model->someAttr = 'someVal';
$clonedModel = Yii::$app->utilities->cloneModel(ModelClass::class,$modelTemp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With