Answer the question
In order to leave comments, you need to log in
How to move code from controller to model?
Hello. There is a controller in Yii2:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$image = $model->image;
if ($model->load(Yii::$app->request->post())) {
$model->files = UploadedFile::getInstance($model, 'image');
if ($model->validate()) {
if ($model->files) {
$name = $model->files->baseName . '.' . $model->files->extension;
$path = Yii::getAlias('@webroot' . '/uploads/') . $name;
$model->files->saveAs($path);
$model->image = $name;
if($model->removeImage) {
$fileRemove = Yii::getAlias('@webroot' . '/uploads/') . $image;
if(file_exists($fileRemove)) {
unlink($fileRemove);
$model->image = '';
}
}
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
else {
return $this->render('update', [
'model' => $model,
]);
}
}
public $files;
public $removeImage;
Article::findOne($id)
Article::find()->where(['id' => $id])->all();
Answer the question
In order to leave comments, you need to log in
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', ['model' => $model]);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question