PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] update the uploaded file yii2

 January 09, 2022     controller, upload, yii, yii2     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing