Не показывает картина при использование CostaRico/yii2-images

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

Добрый день уважаемые программисты. Нужна ваша помощь...
Использую CostaRico/yii2-images вместо картинки выводить вот такое:
image-by-item-and-alias?item=Product1&dirtyAlias=153bf3df2c-1.jpg


view.php

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

<?php

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

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

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

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

    <p>
        <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Delete', ['delete', 'id' => $model->id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?>
    </p>
    <?php $img = $model->getImage(); ?>
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'category_id',
            'name',
            'content:html',
            'price',
            'keywords',
            'description',
            [
                'attribute' => 'image',
                'value' => "<img src='{$img->getUrl()}'>",
                'format' => 'html',
            ],
            'hit',
            'new',
            'sale',
        ],
    ]) ?>


</div>

Модель. Product.php

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

<?php

namespace app\modules\admin\models;

use Yii;

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

    public $image;
    public $gallery;

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

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

    public function getCategory(){
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['category_id', 'name'], 'required'],
            [['category_id'], 'integer'],
            [['content', 'hit', 'new', 'sale'], 'string'],
            [['price'], 'number'],
            [['name', 'keywords', 'description', 'img'], 'string', 'max' => 255],
            [['image'], 'file', 'extensions' => 'png, jpg'],
            [['gallery'], 'file', 'extensions' => 'png, jpg', 'maxFiles' => 4],
        ];
    }

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

    public function upload(){
        if($this->validate()){
            $path = 'upload/store/' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            $this->attachImage($path, true);
            @unlink($path);
            return true;
        }else{
            return false;
        }
    }

    public function uploadGallery(){
        if($this->validate()){
            foreach($this->gallery as $file){
                $path = 'upload/store/' . $file->baseName . '.' . $file->extension;
                $file->saveAs($path);
                $this->attachImage($path);
                @unlink($path);
            }
            return true;
        }else{
            return false;
        }
    }
}

Контроллер. Product.Controller.php

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

<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\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
     */
    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]);
        } else {
            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
     */
    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 ){
                $model->upload();
            }
            unset($model->image);
            $model->gallery = UploadedFile::getInstances($model, 'gallery');
            $model->uploadGallery();

            Yii::$app->session->setFlash('success', "Товар {$model->name} обновлен");
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            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
     */
    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;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

В чем может быть проблема?
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

urichalex писал(а): 2018.05.04, 09:55 А как надо?
Сама картина не показывает... Выводиться текст image-by-item-and-alias?item=Product1&dirtyAlias=153bf3df2c-1.jpg
Аватара пользователя
proctoleha
Сообщения: 298
Зарегистрирован: 2016.07.10, 19:00

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение proctoleha »

'format' => 'raw',
Вот за что я не люблю линукс, так это за свои кривые, временами, руки
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

proctoleha писал(а): 2018.05.04, 10:19 'format' => 'raw',
'format' => 'raw' и 'format' => 'html' оба пробовал. Не помогло.
andku83
Сообщения: 988
Зарегистрирован: 2016.07.01, 10:24
Откуда: Харьков

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение andku83 »

настройки модуля в конфиг добавили?

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

                'format' => 'raw',
                'value' => function ($model) {
                	return "<img src='{$model->getImage()->getUrl()}'>"
                }
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

andku83 писал(а): 2018.05.04, 13:31 настройки модуля в конфиг добавили?

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

                'format' => 'raw',
                'value' => function ($model) {
                	return "<img src='{$model->getImage()->getUrl()}'>"
                }
Да. Вот этот?
web.php

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

<?php

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'language'=>' ru-RU',
    'defaultRoute' => 'category/index',
    'modules' => [
        'admin' => [
            'class' => 'app\modules\admin\Module',
            'layout' => 'admin',
            'defaultRoute' => 'order/index',
        ],
        'yii2images' => [
            'class' => 'rico\yii2images\Module',
            //be sure, that permissions ok
            //if you cant avoid permission errors you have to create "images" folder in web root manually and set 777 permissions
            'imagesStorePath' => 'upload/store', //path to origin images
            'imagesCachePath' => 'upload/cache', //path to resized copies
            'graphicsLibrary' => 'GD', //but really its better to use 'Imagick'
            'placeHolderPath' => '@webroot/upload/store/no-image.png', // if you want to get placeholder when image not exists, string will be processed by Yii::getAlias
            'imageCompressionQuality' => 100, // Optional. Default value is 85.
        ],

    ],
andku83
Сообщения: 988
Зарегистрирован: 2016.07.01, 10:24
Откуда: Харьков

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение andku83 »

mubin_yunusov писал(а): 2018.05.04, 07:51 ... вместо картинки выводить вот такое:
image-by-item-and-alias?item=Product1&dirtyAlias=153bf3df2c-1.jpg
это в каком контексте? Покажите фрагмент HTML до и после этого
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

andku83 писал(а): 2018.05.04, 13:54
mubin_yunusov писал(а): 2018.05.04, 07:51 ... вместо картинки выводить вот такое:
image-by-item-and-alias?item=Product1&dirtyAlias=153bf3df2c-1.jpg
это в каком контексте? Покажите фрагмент HTML до и после этого
Изображение
https://ibb.co/iLSr67

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

[
       'attribute' => 'image',
       'value' => "<img src='{$img->getUrl()}'>",
       'format' => 'html',
],
andku83
Сообщения: 988
Зарегистрирован: 2016.07.01, 10:24
Откуда: Харьков

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение andku83 »

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

                'format' => 'raw',
                'value' => function ($model) {
                	return Html::img($model->getImage()->getUrl(), ['alt' => $model->name]); // или 'alt' => ''
                }
а откуда у вас берется '/2/images' - разбирайтесь по настройкам
mubin_yunusov
Сообщения: 150
Зарегистрирован: 2015.02.05, 11:01
Контактная информация:

Re: Не показывает картина при использование CostaRico/yii2-images

Сообщение mubin_yunusov »

Добавил в config/web.php

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

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '<id:([0-9])+>/images/image-by-item-and-alias' => 'yii2images/images/image-by-item-and-alias',
            ]
        ],
Проблема решено. Но не знаю правильно ли это?
Ответить