Skip to content

Commit

Permalink
fix #1865 Загрузка изображений в товар
Browse files Browse the repository at this point in the history
  • Loading branch information
sabian committed Nov 13, 2017
1 parent 5517328 commit e90b6c6
Show file tree
Hide file tree
Showing 14 changed files with 748 additions and 228 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -3,6 +3,7 @@
Версия 1.2 В разработке
--------------------------

- #1865: Загрузка изображений в товар (@sabian)
- #2606: Дебаг-панель не отображалась, если включить на сайте другой язык (@fazliddin, @sabian)
- #2615: Текст уведомления при создании карты сайта (@dzhedai, @sabian)
- #2616: Очистка кеша после изменения блока контента (@tmsk70, @sabian)
Expand Down
452 changes: 229 additions & 223 deletions composer.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion protected/modules/store/StoreModule.php
Expand Up @@ -10,7 +10,7 @@ class StoreModule extends WebModule
/**
*
*/
const VERSION = '1.1';
const VERSION = '1.2';

/**
* @var
Expand Down Expand Up @@ -95,6 +95,7 @@ public function getDependencies()
{
return [
'comment',
'gallery',
];
}

Expand Down
194 changes: 194 additions & 0 deletions protected/modules/store/controllers/ProductImageBackendController.php
@@ -0,0 +1,194 @@
<?php

use yupe\components\controllers\BackController;

/**
* Class ProductImageBackendController
*/
class ProductImageBackendController extends BackController
{
/**
* @var ProductRepository
*/
private $productRepository;

/**
*
*/
public function init()
{
parent::init();

$this->productRepository = Yii::app()->getComponent('productRepository');
}

/**
* @return array|mixed
*/
public function filters()
{
return CMap::mergeArray(
parent::filters(),
[
'postOnly + delete, addImages',
]
);
}

/**
* @param integer $id Product Id
* @throws CHttpException
*/
public function actionIndex($id)
{
$product = $this->productRepository->getById($id, []);
$model = new ProductImage();

if (null === $product) {
throw new CHttpException(404);
}

$this->render('index', [
'product' => $product,
'model' => $model,
]);
}

/**
* Функция добавления группы изображений
*
* @param int $id - id-галереи
*
* @return void
*
* @throws CHttpException
* @throws CException
*/
public function actionAddImages($id)
{
$product = $this->productRepository->getById($id, []);
$image = new ProductImage();
$image->product_id = $product->id;

if (null === $product) {
throw new CHttpException(404);
}

if (($imageData = Yii::app()->getRequest()->getPost('ProductImage')) !== null) {
$imageData = $imageData[$_FILES['ProductImage']['name']['name']];

$this->_addImage($image, $imageData, $product);
if ($image->hasErrors()) {
$data[] = ['error' => $image->getErrors()];
} else {
$data[] = [
'name' => $image->name,
'type' => $_FILES['ProductImage']['type']['name'],
'size' => $_FILES['ProductImage']['size']['name'],
'url' => $image->getImageUrl(),
'thumbnail_url' => $image->getImageUrl(80, 80),
'delete_url' => $this->createUrl(
'/store/productImageBackend/deleteImage',
[
'id' => $image->id,
'method' => 'uploader'
]
),
'delete_type' => 'GET'
];
}

Yii::app()->ajax->raw($data);
} else {
throw new CHttpException(
404,
Yii::t('StoreModule.store', 'Page not found!')
);
}
}

/**
* Метод добавления одной фотографии:
*
* @param ProductImage $image - инстанс изображения
* @param mixed $imageData - POST-массив данных
* @param Product $product - инстанс галереи
*
* @return void
*
*/
private function _addImage(ProductImage $image, array $imageData, Product $product)
{
try {
$transaction = Yii::app()->getDb()->beginTransaction();
$image->setAttributes($imageData);

if ($image->save()) {

$transaction->commit();

if (Yii::app()->getRequest()->getPost('ajax') === null) {
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::SUCCESS_MESSAGE,
Yii::t('StoreModule.store', 'Image created')
);
$this->redirect(['/store/productImageBackend/index', 'id' => $product->id]);
}
}
} catch (Exception $e) {

$transaction->rollback();

Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::ERROR_MESSAGE,
$e->getMessage()
);
}
}

/**
* Ajax/Get-обёртка для удаления изображения:
*
* @param int $id - id-изображения
* @param int $product - id-товара
*
* @return void
*
* @throws CHttpException
*/
public function actionDeleteImage($id, $product)
{
$image = ProductImage::model()->findByPk($id);

if ($image === null) {
throw new CHttpException(
404,
Yii::t('StoreModule.store', 'Page not found!')
);
}

$message = Yii::t(
'StoreModule.store',
'Image #{id} {result} deleted',
[
'{id}' => $id,
'{result}' => ($result = $image->delete())
? Yii::t('StoreModule.store', 'success')
: Yii::t('StoreModule.store', 'not')
]
);

if (Yii::app()->getRequest()->getIsPostRequest() && Yii::app()->getRequest()->getIsAjaxRequest) {
$result === true
? Yii::app()->ajax->success($message)
: Yii::app()->ajax->failure($message);
}

Yii::app()->getUser()->setFlash(
$result ? yupe\widgets\YFlashMessages::SUCCESS_MESSAGE : yupe\widgets\YFlashMessages::ERROR_MESSAGE,
$message
);

$this->redirect(['/store/productImageBackend/index', 'id' => $product]);
}
}
9 changes: 8 additions & 1 deletion protected/modules/store/messages/ru/store.php
@@ -1,6 +1,5 @@
<?php
return [
'View product on site' => 'Смотреть на сайте',
'% to the price' => '% к цене',
'*unknown*' => '*неизвестно*',
'--choose--' => '--выберите--',
Expand Down Expand Up @@ -142,10 +141,13 @@
'Id' => 'Id',
'ID' => 'ID',
'Illegal characters in {attribute}' => 'Запрещенные символы в поле {attribute}',
'Image #{id} {result} deleted' => 'Изображение #{id} {result} удалено!',
'Image alt' => 'Текст тега alt',
'Image created' => 'Изображение добавлено!',
'Image groups' => 'Группы изображений',
'Image title' => 'Текст тега title',
'Image' => 'Изображение',
'Images not found' => 'Изображения не найдены',
'Images' => 'Изображения',
'Import' => 'Импорт',
'In stock' => 'В наличии',
Expand Down Expand Up @@ -177,6 +179,8 @@
'Manage products' => 'Все товары',
'Manage' => 'Управление',
'manage' => 'управление',
'Mass image upload' => 'Массовая загрузка изображений',
'Mass upload alert' => 'После сохранения товара будет доступна функция массовой загрузки изображений',
'Maximum size (in bytes)' => 'Максимальный размер (в байтах)',
'Menu items order' => 'Порядок следования в меню',
'Meta description' => 'Описание',
Expand All @@ -190,6 +194,7 @@
'Not active' => 'Не доступен',
'Not available' => 'Нет в наличии',
'Not in stock' => 'Нет в наличии',
'not' => 'не',
'Number' => 'Число',
'On moderation' => 'На модерации',
'or' => 'или',
Expand Down Expand Up @@ -265,6 +270,7 @@
'Store module' => 'Модуль для создания интернет-магазина',
'Store' => 'Магазин',
'Structure' => 'Структура',
'success' => 'успешно',
'Targeting category was not found!' => 'Целевая категория не найдена!',
'team@yupe.ru' => 'team@yupe.ru',
'Template' => 'Шаблон',
Expand Down Expand Up @@ -309,6 +315,7 @@
'View producer list' => 'Просмотреть список производителей',
'View producer' => 'Просмотреть производителя',
'View product list' => 'Просмотреть список товаров',
'View product on site' => 'Смотреть на сайте',
'View product' => 'Просмотреть товар',
'View type' => 'Просмотреть тип',
'View' => 'Просмотр',
Expand Down
9 changes: 9 additions & 0 deletions protected/modules/store/views/productBackend/_form.php
Expand Up @@ -329,6 +329,15 @@
</div>

<div class="tab-pane" id="images">
<?php if ($model->getIsNewRecord()): ?>
<div class="row">
<div class="col-lg-6">
<div class="alert alert-success">
<?= Yii::t("StoreModule.store", "Mass upload alert"); ?>
</div>
</div>
</div>
<?php endif; ?>
<div class="row form-group">
<div class="col-xs-2">
<?= Yii::t("StoreModule.store", "Images"); ?>
Expand Down
17 changes: 14 additions & 3 deletions protected/modules/store/views/productBackend/index.php
Expand Up @@ -172,12 +172,23 @@
'frontViewButtonUrl' => function($data){
return ProductHelper::getUrl($data);
},
'template' => '{front_view} {view} {update} {images} {delete}',
'buttons' => [
'front_view' => [
'visible' => function ($row, $data) {
return $data->status == Product::STATUS_ACTIVE;
}
]
return $data->status == Product::STATUS_ACTIVE;
}
],
'images' => [
'icon' => 'fa fa-fw fa-picture-o',
'label' => Yii::t('StoreModule.store', 'Images'),
'url' => function ($data) {
return Yii::app()->createUrl('/store/productImageBackend/index', ['id' => $data->id]);
},
'options' => [
'class' => 'images btn btn-sm btn-default',
]
],
]
],
],
Expand Down
8 changes: 8 additions & 0 deletions protected/modules/store/views/productBackend/update.php
Expand Up @@ -52,6 +52,14 @@
'csrf' => true,
]
],
[
'icon' => 'fa fa-fw fa-picture-o',
'label' => Yii::t('StoreModule.store', 'Mass image upload'),
'url' => [
'/store/productImageBackend/index',
'id' => $model->id
]
],
];
?>
<div class="page-header">
Expand Down
20 changes: 20 additions & 0 deletions protected/modules/store/views/productImageBackend/_add.php
@@ -0,0 +1,20 @@
<?php
$this->widget(
'bootstrap.widgets.TbFileUpload',
[
'id' => 'fileUploader',
'url' => $this->createUrl("/store/productImageBackend/addImages", ['id' => $product->id]),
'model' => $model,
'attribute' => 'name',
'multiple' => true,
'formView' => 'store.views.productImageBackend._tform',
'uploadView' => 'store.views.productImageBackend._upload',
'options' => [
'maxFileSize' => Yii::app()->getModule('image')->maxSize,
'acceptFileTypes' => 'js:/(\.|\/)(' . implode(
'|',
Yii::app()->getModule('image')->allowedExtensions()
) . ')$/i',
]
]
);
26 changes: 26 additions & 0 deletions protected/modules/store/views/productImageBackend/_image.php
@@ -0,0 +1,26 @@
<div class="image-wrapper">
<div class="gallery-thumbnail">
<?= CHtml::link(
CHtml::image($image->getImageUrl(190, 190), $image->alt),
$image->getImageUrl(),
[
'class' => 'gallery-image',
'title' => $image->title,
]
); ?>
</div>
<div class="btn-group btn-group-xs" role="group">
<?= CHtml::link(
'<i class="fa fa-fw fa-times"></i>',
Yii::app()->createAbsoluteUrl('store/productImageBackend/deleteImage', [
'id' => $image->id,
'product' => $product->id,
]),
[
'class' => 'btn btn-danger',
'data-toggle' => 'tooltip',
'title' => Yii::t('StoreModule.store', 'Delete'),
]
); ?>
</div>
</div>

0 comments on commit e90b6c6

Please sign in to comment.