I am trying to run an application in Yii2
I tried to upload a user profile picture and it works greatly
but the problem starts when I try to update the name file. It shows me an error like Call to a member function saveAs() on a non-object
.
I even tried to update without any changes.. even that time also show me the same error...
but error goes if I change the pic.
this is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// get the instance of uploaded file
$imageName = $model->user_username;
$model->file = UploadedFile::getInstance($model,'user_avatar');
$model->file->saveAs( '/uploads/'.$imageName.'.'.$model->file->extension );
//save the path in DB..
$model->user_avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->user_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
The model rules
public function rules()
{
return [
[['user_email', 'user_password'], 'required'],
// [['user_password'], 'required'],
[['user_username'], 'string', 'max' => 45],
[['user_first_name'], 'required'],
[['user_app_user_id'], 'required',
[['user_type','user_app_name','user_status'], 'string'],
[['user_app_user_id'], 'integer'],
[['user_rememberMe'], 'boolean'],
[['user_first_name', 'user_last_name'], 'string', 'max' => 100],
[['user_email'], 'string', 'max' => 150],
[['user_password'], 'string', 'min'=>6],
[['user_password'], 'string', 'max' => 40,
[['user_avatar'],'file'],
//[['user_avatar'], 'string', 'max' => 500],
[['user_verification_code','user_auth_key'], 'string'],
[['user_email'], 'email'],
[['user_email'], 'filter', 'filter' => 'trim'],
];
}
Your code requires file upload. You should just add condition here:
if ($model->file = UploadedFile::getInstance($model,'user_avatar')) {
$model->file->saveAs( '/uploads/'.$imageName.'.'.$model->file->extension );
//save the path in DB..
$model->user_avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
}