0

Не могу загрузить файл на сервер. Выдает ошибку:

Call to a member function saveAs() on a non-object

Вот моя модель:

<?php
namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\web\UploadedFile;
class User extends ActiveRecord implements IdentityInterface{
    public $file;

    public function rules()
    {
        return [
            [['file'], 'file']
        ];
    }

    public function setPassword($password){
        $this->password=sha1($password);
    }

    public function validatePassword($password){
        return $this->password === sha1($password);
    }

    public function attributeLabels()
    {
        return [
            'file'=>'Main photo',
        ];
    }

    public function fileInsert(){
        $this->file=UploadedFile::getInstance($this,'file');
        $this->file->saveAs('img/avs/'.$this->id.'/'.$this->file->baseName.'.'.$this->file->extension);
        $this->img='img/avs/'.$this->id.'/'.$this->file->baseName.'.'.$this->file->extension;
        return $this->img;
    }

    public static function findIdentity($id)
    {
        return self::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        // TODO: Implement getAuthKey() method.
    }

    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }
}

Здесь функция fileInsert. Вот контроллер, где я использую (см. функция actionIndex):

<?php

namespace app\modules\User\controllers;

use app\models\Posts;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\web\User;
use Yii;
use app\models\Info;

class InfoController extends Controller{
    public $layout = '/info/main';

    public function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
        list($w_i, $h_i, $type) = getimagesize($file_input);
        if (!$w_i || !$h_i) {
            echo 'Невозможно получить длину и ширину изображения при уменьшении';
            return;
        }
        $types = array('','gif','jpeg','png');
        $ext = $types[$type];
        if ($ext) {
            $func = 'imagecreatefrom'.$ext;
            $img = $func($file_input);
        } else {
            echo 'Некорректный формат файла';
            return;
        }
        if ($percent) {
            $w_o *= $w_i / 100;
            $h_o *= $h_i / 100;
        }
        if (!$h_o) $h_o = $w_o/($w_i/$h_i);
        if (!$w_o) $w_o = $h_o/($h_i/$w_i);
        $img_o = imagecreatetruecolor($w_o, $h_o);
        imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
        if ($type == 2) {
            return imagejpeg($img_o,$file_output,100);
        } else {
            $func = 'image'.$ext;
            return $func($img_o,$file_output);
        }
    }

    public function actionIndex()
    {
        $id=Yii::$app->user->identity->id;
        $user = \app\models\User::findOne(['id' => Yii::$app->user->identity->id]);
        if(Yii::$app->request->post('User')){
            $user->name=$_POST['User']['name'];
            $user->surname=$_POST['User']['surname'];
            $d=strtotime($_POST['User']['date']);
            $user->date=date("Y-m-d", $d);
            $user->country=$_POST['User']['country'];
            $user->city=$_POST['User']['city'];
            $user->about=$_POST['User']['about'];
            $user->fileInsert();
            echo "Loaded";die();
            if($user->validate()){
                $user->save();
                echo "success";
            }
        }
        return $this->render('info', ['user' => $user]);
    }
}

И вот вьюха:

<?php
namespace yii\jui;
use yii\widgets\ActiveForm;
use yii\jui\AutoComplete;
use zxbodya\yii2\tinymce\TinyMce;
use yii\web\UploadedFile;
?>

<?php
$form = ActiveForm::begin(['class'=>'form-horizontal']);?>
<?= $form->field($user,'file')->fileInput();?>
<?= $form->field($user,'name')->textInput();?>
<?= $form->field($user,'surname')->textInput();?>

<?= $form->field($user,'date')->widget(DatePicker::className()) ?>
<?= $form->field($user, 'country')->widget(\yii\jui\AutoComplete::classname(), [
    'clientOptions' => [
        'source' => ['USA', 'RUS','UA'],
    ],
]) ?>
<?= $form->field($user, 'city')->widget(\yii\jui\AutoComplete::classname(), [
    'clientOptions' => [
        'source' => ['Kyjv', 'Moskov','Khmelnitsky'],
    ],
]) ?>
    <?=$form->field($user, 'about')->widget(
    TinyMce::className(),
    ['spellcheckerUrl'=>'http://speller.yandex.net/services/tinyspell']
) ?>

<button type="submit" class="btn btn-primary">save</button>
<?php
ActiveForm::end();
?>

Помогите решить проблему.

1 ответ 1

1

В методе actionIndex вы получаете данные вызывая метод:

$user = \app\models\User::findOne(['id' => Yii::$app->user->identity->id]);

Вам стоит создавать объект User отдельно, т.е.:

$user = new \app\models\User();

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.