1

I'm trying to upload a profile picture without ActiveForm or Model.

According to Yii2 docs we can use AdHoc Validation Rule, In this example it's using email validation but i need file validation.

What i've tried:

public function actionPicture() {

    /* @var $user \app\models\User */
    /* @var $validator \yii\validators\FileValidator */

    $validator = new FileValidator(['extensions' => ['png','jpg']]); // Setting Allowed Extensions

    $file = UploadedFile::getInstanceByName('avatar'); // Get File Object byName

    if( $validator->validate($file, $errors) ) { // Validate here
        $user = User::findOne(['id' => Yii::$app->user->getId()]);
        $user->avatar = 'profile-'.$user->id.'.'.$file->getExtension();
        if($user->save(false)) {
            $file->saveAs(Yii::getAlias('@upload_dir').'/'.$user->avatar);
            Yii::$app->user->setIdentity($user);
            yii::$app->session->setFlash('success','Profile Picture updated successfully');
        }

    } else {
        yii::$app->session->setFlash('danger',$errors);
    }

    return $this->redirect(['index']);

}

My Question: In the above code is it the standard way to use FileValidator with out active forms.

Note: I know we can use Yii2 File Upload, but it's using Model which is not i wanted

Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45

0 Answers0