yii2-images

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
vano.mig
Сообщения: 73
Зарегистрирован: 2016.11.21, 10:25

yii2-images

Сообщение vano.mig »

Привет, ребята... Есть проблема - не выводятся фото в представлении... в таблицу загружаются, .... а вместо фото при вызове getUrl() такое: /yii2images/images/image-by-item-and-alias?item=&dirtyAlias=placeHolder.png и еще Class 'abeautifulsite\SimpleImage' not found
метод getPathToOrigin() тоже не работал, пока в модуле /vendor/costa-rico/yii2-images/models/Image.php в

public function getPathToOrigin(){
$base = $this->getModule()->getStorePath();
строку
$filePath = "/".$base.DIRECTORY_SEPARATOR.$this->filePath;
не заменил
$filePath = "/".$base."/".$this->filePath;

return $filePath;
}
больше ничего не менял... уже 3 суток не могу разобраться, подскажите!

модель

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

<?php

namespace app\modules\admin\models;

use Yii;

/**
 * This is the model class for table "products".
 *
 * @property integer $id
 * @property string $title
 * @property integer $article
 * @property string $description
 * @property string $price
 * @property integer $category_id
 */
class Products extends \yii\db\ActiveRecord
{
    public $image;
    public $gallery;

    public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ]
        ];
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'products';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'article', 'description', 'price', 'category_id'], 'required'],
            [['article', 'category_id'], 'integer'],
            [['description'], 'string'],
            [['title'], 'string', 'max' => 50],
            [['price'], 'string', 'max' => 10],
            [['image'], 'file', 'extensions' => 'jpeg, jpg, png, giff'],
            [['gallery'], 'file', 'extensions' => 'jpeg, jpg, png, giff', 'maxFiles' => 4],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Название',
            'article' => 'Артикул',
            'description' => 'Описание',
            'price' => 'Цена',
            'category_id' => '№ категории',
            'image' => 'Изображение',
        ];
    }

    public function upload() {
        if ($this->validate()) {
            $path = "images/store". "/". $this->image->baseName.".".$this->image->extension;
            //print_r($path); die;
            $this->image->saveAs($path);
            $this->attachImage($path);
            return true;
        } else {
            return false;
        }
    }
}
контроллер

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

<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\Products;
use app\modules\admin\models\ProductsSearch;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\web\UploadedFile;


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

    /**
     * Lists all Products models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (!\Yii::$app->user->can('Manager')) {
            throw new ForbiddenHttpException('У Вас нет прав доступа к данной странице!');
        }
        $this->setMeta("IKAR | Админ-панель");
        $searchModel = new ProductsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Products model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        if (!\Yii::$app->user->can('Manager')) {
            throw new ForbiddenHttpException('У Вас нет прав доступа к данной странице!');
        }
        $this->setMeta("IKAR | Админ-панель");
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Products model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if (!\Yii::$app->user->can('Manager')) {
            throw new ForbiddenHttpException('У Вас нет прав доступа к данной странице!');
        }
        $this->setMeta("IKAR | Админ-панель");
        $model = new Products();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', "Добавлен новый продукт");
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Products model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (!\Yii::$app->user->can('Manager')) {
            throw new ForbiddenHttpException('У Вас нет прав доступа к данной странице!');
        }
        $this->setMeta("IKAR | Админ-панель");
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->image = UploadedFile::getInstance($model, 'image');
            if ($model->image->error == 0) {
                if ($model->upload()) {
                    Yii::$app->session->setFlash('success', "Продукт {$model->title} успешно изменен");
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Products model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (!\Yii::$app->user->can('Manager')) {
            throw new ForbiddenHttpException('У Вас нет прав доступа к данной странице!');
        }
        $this->findModel($id)->delete();
        Yii::$app->session->setFlash('success', "Продукт удален");
        return $this->redirect(['index']);
    }

    /**
     * Finds the Products model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Products the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Products::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
виды

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

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Products */

//$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => 'Products', 'url' => ['index']];
$this->params['breadcrumbs'][] = $model->title;
?>
<div class="products-view">

    <h1><?= Html::encode($model->title) ?></h1>

    <p>
        <?= Html::a('Изменить', ['update', 'id' => $model->id], ['class' => 'btn btn-success']) ?>
        <?= Html::a('Удалить', ['delete', 'id' => $model->id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Вы уверены, что хотите удальть данный продукт?',
                'method' => 'post',
            ],
        ]) ?>
    </p>

    <?php $img  = $model->getImage(); echo $img->getUrl();?>
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'title',
            'article',
            'description:html',
            'price',
            'category_id',
            [
                'attribute' => 'image',
                'value' => "<img src='{$img->getUrl()}'>",
                'format' => 'html',
            ],
        ],
    ]) ?>

</div>

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

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use mihaildev\ckeditor\CKEditor;
use mihaildev\elfinder\ElFinder;
mihaildev\elfinder\Assets::noConflict($this);

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Products */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="products-form">

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

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

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

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

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

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

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Создать' : 'Изменить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>
befrees
Сообщения: 1
Зарегистрирован: 2017.01.21, 10:05

Re: yii2-images

Сообщение befrees »

Тоже такое было
решил, добавив @webroot в настройках модуля (config/web.php)

'imagesStorePath' => '@webroot/images/store', //path to origin images
'imagesCachePath' => '@webroot/images/cache', //path to resized copies
Ответить