I'm working on a Yii2 application and have encountered an issue when attempting to duplicate a model along with its uploaded files. I'm using Yii2's UploadedFile for file uploads. The challenge is that the uploaded files (imageFiles) are not being successfully copied to the new model. Here's my code:
public function actionDuplicate($id)
{
$existingModel = $this->findModel($id);
$model = new Task();
// Copy attributes from the existing model
$model->attributes = $existingModel->attributes;
// Manually copy the imageFiles property if it exists
if (isset($existingModel->imageFiles) && is_array($existingModel->imageFiles)) {
$model->imageFiles = [];
foreach ($existingModel->imageFiles as $file) {
$model->imageFiles[] = $file;
}
}
// Reset primary key
$model->id = null;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// renders view
} else {
// Render the create form with the new model
return $this->render('create', [
'model' => $model,
]);
}
}
The code copies most attributes correctly, but the imageFiles property is not being included in the new model. I've double-checked that the imageFiles property exists in the source model ($existingModel) and that it's an array. What could be causing this issue, and how can I ensure that the imageFiles are correctly copied to the new model
EDIT : The imageFiles attribute is an array of files declared inside the Model, and it's handled with the following upload function:
public function upload()
{
if ($this->validate()) {
$path = Yii::getAlias('@doc_attivita') . "/" . $this->id;
FileHelper::createDirectory($path, $mode = 0775, $recursive = true);
foreach ($this->imageFiles as $file) {
$file->saveAs($path . "/" . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}