Использую 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>
Код: Выделить всё
<?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;
}
}
}
Код: Выделить всё
<?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.');
}
}
}