Sunday, January 9, 2022

[FIXED] update the uploaded file yii2

Issue

I have used following to upload image and save it in server and database. Now I want to write a controller to update the uploaded image. how to do it???

controller

public function actionInvitfile()
{
    $model = new Applicants();
    $imgName = Yii::$app->user->identity->id;

        if($model->load(Yii::$app->request->post())){
        $model->file = UploadedFile::getInstance($model, 'file');
        $model->file->saveAs('uploads/invitfile/' . $imgName . '.' . $model->file->extension);
        $model->invitations_file='uploads/invitfile/'. $imgName . '.' . $model->file->extension;
        $model->save(false);
        }
   return $this->goHome();
}

Model

    class Applicants extends \yii\db\ActiveRecord
{
    public $file;
    public static function tableName()
    {
        return 'applicants';
    }

    public function rules()
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
        ];
    }

Please, Help me!)


Solution

I think this can work

public function actionUpdate($id)
    {
         $imgName = Yii::$app->user->identity->id;
         $model = Applicants->findModel($id);
        if($model->load(Yii::$app->request->post())){

         unlink($model->invitations_file); 


         $model->file = UploadedFile::getInstance($model, 'file');
         $model->file->saveAs('uploads/invitfile/' . $imgName . '.' . $model->file->extension);
         $model->invitations_file='uploads/invitfile/'. $imgName . '.' . $model->file->extension;
         $model->save(false);
        }
   return $this->goHome();

    }

but here you have official documentation of the kartij blog where you can learn much more and have a better answer to your problem:
http://webtips.krajee.com/advanced-upload-using-yii2-fileinput-widget/



Answered By - eborrallo

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.