Ошибка при загрузке картинки

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Cyrus
Сообщения: 1
Зарегистрирован: 2020.07.20, 15:02

Ошибка при загрузке картинки

Сообщение Cyrus »

Добрый день.
Использую - https://github.com/CostaRico/yii2-images
Шаблон - advanced.

Настройки прописал в backend/config/main.php
Миграцию провел.

Ошибка при вызове метода $model->attachImage

Сами фотографии сохраняются, тут ок.
Сохраняются в папке backend/web/upload/store/
Но не происходит запись в бд - image и ловлю вот такую ошибку:
Setting unknown property: rico\yii2images\Module::imageCompressionQuality

Полный текст ошибки:

Код: Выделить всё

Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: rico\yii2images\Module::imageCompressionQuality
1. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Component.phpat line 209
200201202203204205206207208209210211212213214215216217218                $behavior->$name = $value;
                return;
            }
        }
 
        if (method_exists($this, 'get' . $name)) {
            throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
        }
 
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
 
    /**
     * Checks if a property is set, i.e. defined and not null.
     *
     * This method will check in the following order and act accordingly:
     *
     *  - a property defined by a setter: return whether the property is set
     *  - a property of a behavior: return whether the property is set
2. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/BaseYii.php at line 558– yii\base\Component::__set()
3. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/BaseObject.php at line 107– yii\BaseYii::configure()
4. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Module.php at line 158– yii\base\BaseObject::__construct()
5. yii\base\Module::__construct()
6. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/di/Container.php at line 400– ReflectionClass::newInstanceArgs()
7. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/di/Container.php at line 159– yii\di\Container::build()
8. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/BaseYii.php at line 365– yii\di\Container::get()
9. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Module.php at line 427– yii\BaseYii::createObject()
10. in /home/cyrus/yii2_shop/vendor/costa-rico/yii2-images/ModuleTrait.php at line 27– yii\base\Module::getModule()
21222324252627282930313233    /**
     * @return null|\rico\yii2images\Module
     */
    protected function getModule()
    {
        if ($this->_module == null) {
            $this->_module = \Yii::$app->getModule('yii2images');
        }
 
        if(!$this->_module){
            throw new Exception("\n\n\n\n\nYii2 images module not found, may be you didn't add it to your config?\n\n\n\n");
        }
 
11. in /home/cyrus/yii2_shop/vendor/costa-rico/yii2-images/behaviors/ImageBehave.php at line 63– rico\yii2images\behaviors\ImageBehave::getModule()
57585960616263646566676869        }
 
        $pictureFileName =
            substr(md5(microtime(true) . $absolutePath), 4, 6)
            . '.' .
            pathinfo($absolutePath, PATHINFO_EXTENSION);
        $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
        $storePath = $this->getModule()->getStorePath($this->owner);
 
        $newAbsolutePath = $storePath .
            DIRECTORY_SEPARATOR . $pictureSubDir .
            DIRECTORY_SEPARATOR . $pictureFileName;
 
12. rico\yii2images\behaviors\ImageBehave::attachImage()
13. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Component.php at line 297– call_user_func_array()
14. in /home/cyrus/yii2_shop/backend/controllers/ProductController.php at line 101– yii\base\Component::__call()
9596979899100101102103104105106107            if($model->image )
            {
                $path = 'upload/store/' . $model->image->baseName . '.' . $model->image->extension;
//                $path = Yii::getAlias('@webroot/upload/store/').$model->image->baseName . '.' . $model->image->extension;
                $model->image->saveAs($path);
 
                $model->attachImage($path);
            }
 
            Yii::$app->session->setFlash('success',"Товар {$model->name} обновлен");
            return $this->redirect(['view', 'id' => $model->id]);
        }
 
15. backend\controllers\ProductController::actionUpdate()
16. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/InlineAction.php at line 57– call_user_func_array()
17. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Controller.php at line 180– yii\base\InlineAction::runWithParams()
18. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Module.php at line 528– yii\base\Controller::runAction()
19. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/web/Application.php at line 103– yii\base\Module::runAction()
979899100101102103104105106107108109            $params = $this->catchAll;
            unset($params[0]);
        }
        try {
            Yii::debug("Route requested: '$route'", __METHOD__);
            $this->requestedRoute = $route;
            $result = $this->runAction($route, $params);
            if ($result instanceof Response) {
                return $result;
            }
 
            $response = $this->getResponse();
            if ($result !== null) {
20. in /home/cyrus/yii2_shop/vendor/yiisoft/yii2/base/Application.php at line 386– yii\web\Application::handleRequest()
21. in /home/cyrus/yii2_shop/backend/web/index.php at line 17– yii\base\Application::run()
Контроллер

Код: Выделить всё

<?php

namespace backend\controllers;

use Yii;
use backend\models\Product;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Product::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Product();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success',"Товар {$model->name} создан");
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            $model->image = UploadedFile::getInstance($model,'image');

            if($model->image )
            {
                $path = 'upload/store/' . $model->image->baseName . '.' . $model->image->extension;
//                $path = Yii::getAlias('@webroot/upload/store/').$model->image->baseName . '.' . $model->image->extension;
                $model->image->saveAs($path);

                $model->attachImage($path);
            }

            Yii::$app->session->setFlash('success',"Товар {$model->name} обновлен");
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

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

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Модель:

Код: Выделить всё

<?php

namespace backend\models;


/**
 * This is the model class for table "product".
 *
 * @property string $id
 * @property int|null $category_id
 * @property string|null $name
 * @property string|null $content
 * @property int $price
 * @property string|null $keywords
 * @property string|null $description
 * @property string|null $img
 * @property int $hit
 * @property int $new
 * @property int $sale
 *
 * @property Category $category
 */
class Product extends \yii\db\ActiveRecord
{

    public $image;

    public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['category_id', 'price', 'hit', 'new', 'sale'], 'integer'],
            [['content'], 'string'],
            [['id', 'name', 'keywords', 'description'], 'string', 'max' => 255],
            [['id'], 'unique'],
            [['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'Id товара',
            'category_id' => 'Категория',
            'name' => 'Название',
            'content' => 'Описание',
            'price' => 'Цена',
            'keywords' => 'Ключевые слов',
            'description' => 'Мета-описание',
            'image' => 'Фото',
            'hit' => 'Хит',
            'new' => 'Новинка',
            'sale' => 'Распродажа',
        ];
    }

    /**
     * Gets query for [[Category]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }
}

Вид формы:

Код: Выделить всё

<?php

use mihaildev\ckeditor\CKEditor;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use mihaildev\elfinder\ElFinder;

/* @var $this yii\web\View */
/* @var $model backend\models\Product */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="product-form">

    <?php $form = ActiveForm::begin(['options'=>['enctype'=> 'multipart/form-data']]); ?>

    <div class="form-group field-product_category_id">
        <label class="control-label" for="product_category_id">Верхний уровень</label>
        <select id="product_category_id" class="form-control" name="Product[category_id]">
            <?= \common\components\MenuWidget::widget(['tpl'=> 'select_product', 'model' => $model]) ?>
        </select>
    </div>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>


    <?php
    echo $form->field($model, 'content')->widget(CKEditor::className(), [
        'editorOptions' => ElFinder::ckeditorOptions('elfinder',[]),
    ]);
    ?>

    <?= $form->field($model, 'price')->textInput() ?>

    <?= $form->field($model, 'keywords')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'image')->fileInput() ?>

    <?= $form->field($model, 'hit')->checkbox(['0','1']) ?>

    <?= $form->field($model, 'new')->checkbox(['0','1'])?>

    <?= $form->field($model, 'sale')->checkbox(['0','1']) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

Ответить