S
S
Sergey Beloventsev2017-06-09 19:04:19
Yii
Sergey Beloventsev, 2017-06-09 19:04:19

Why does "Call to a member function saveAs() on null" error occur?

here is the controller

public function actionCreate(){
  $module=$this->module;
  $model= new MenuGet();
  $uploadModel=new UploadImage();
  if (Yii::$app->request->isAjax) {
       $request=Yii::$app->request;
        if($request->isPost){
        $fileName = 'file';
        if (isset($_FILES[$fileName])) {
        $file = \yii\web\UploadedFile::getInstanceByName($fileName);
       $uplImg=$uploadModel->upload($file ,$module);
        if ($uplImg) {
        return $this->render('create', [
              'model' => $model,
               'module' => $module,
                'uploadModel' => $uploadModel
        ]);
         }
     }
}

here is UploadImage
class UploadImage extends Model
{
    public $file;
    public function rules()
    {
        return [
            [['file'], 'file','skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'],
        ];
    }
    public function upload($fileName,$module){
        
        $basePath=date('Y').'/'.date('m');
        $uploadPath =$module->imageDownloadPath.''.$basePath;
        if (file_exists($uploadPath)) {
        } else {
            mkdir($uploadPath, 0777, true);
        }
        $file = \yii\web\UploadedFile::getInstanceByName($fileName);
        $filenames=$this->traranslitImg($file->name);
        if ($this->validate()) {
            if(file_exists($uploadPath)) {
            } else {
                mkdir($uploadPath, 0777, true);
            }
            if ($this->file->saveAs($uploadPath . '/' . $filenames)){
                $this->imagerisize($uploadPath, $filenames,$module);
                return true;
            };
        } else {
            return var_dump($this->getErrors());
        }
    }

the picture is loaded via dropzone but the answer comes
Exception 'Error' with message 'Call to a member function saveAs() on null'
in /var/www/magaz.lc/vendor/sirgalas/yii2-wordperss-menu/models/UploadImage.php:41

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Arman, 2017-06-09
@Arik

Lots of bugs, good to read the Yii docs
. Now it doesn't work because you didn't assign a value to the $this->file property. Either change $this->file to $file, because it is an instance of an uploaded file, or, better yet, take the code for working with the instance into the controller and do $uploadModel->file = \yii\web\UploadedFile::getInstanceByName($ filename);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question