Skip to content

Commit eeae38d

Browse files
committed
update feature save and edit tag
1 parent 2df118a commit eeae38d

File tree

8 files changed

+164
-39
lines changed

8 files changed

+164
-39
lines changed

Controller/Adminhtml/Tag.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,9 @@ public function __construct(
4242
* Initialize requested category and put it into registry.
4343
* Root category can be returned, if inappropriate store/category is specified
4444
*
45-
* @param bool $getRootInstead
4645
* @return \Lof\ProductTags\Model\Tag|false
4746
*/
48-
protected function _initCategory($getRootInstead = false)
47+
protected function _initTag()
4948
{
5049
$tagId = $this->resolveTagId();
5150
$storeId = $this->resolveStoreId();
@@ -59,7 +58,7 @@ protected function _initCategory($getRootInstead = false)
5958
$this->_objectManager->get(\Magento\Framework\Registry::class)->register('current_tag', $tag);
6059
$this->_objectManager->get(\Magento\Cms\Model\Wysiwyg\Config::class)
6160
->setStoreId($storeId);
62-
return $category;
61+
return $tag;
6362
}
6463

6564
/**
@@ -69,7 +68,7 @@ protected function _initCategory($getRootInstead = false)
6968
*/
7069
private function resolveTagId() : int
7170
{
72-
$tagId = (int)$this->getRequest()->getParam('id', false);
71+
$tagId = (int)$this->getRequest()->getParam('tag_id', false);
7372

7473
return $tagId ?: (int)$this->getRequest()->getParam('entity_id', false);
7574
}

Controller/Adminhtml/Tag/Edit.php

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
/**
1212
* Edit CMS page action.
1313
*/
14-
class Edit extends \Magento\Backend\App\Action implements HttpGetActionInterface
14+
class Edit extends \Lof\ProductTags\Controller\Adminhtml\Tag implements HttpGetActionInterface
1515
{
1616
/**
1717
* Authorization level of a basic admin session
@@ -72,21 +72,9 @@ protected function _initAction()
7272
public function execute()
7373
{
7474
// 1. Get ID and create model
75-
$id = $this->getRequest()->getParam('tag_id');
76-
$model = $this->_objectManager->create(\Lof\ProductTags\Model\Tag::class);
77-
75+
$tag = $this->_initTag();
76+
$id = $tag->getId();
7877
// 2. Initial checking
79-
if ($id) {
80-
$model->load($id);
81-
if (!$model->getId()) {
82-
$this->messageManager->addErrorMessage(__('This tag no longer exists.'));
83-
/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
84-
$resultRedirect = $this->resultRedirectFactory->create();
85-
return $resultRedirect->setPath('*/*/');
86-
}
87-
}
88-
89-
$this->_coreRegistry->register('product_tag', $model);
9078

9179
// 5. Build edit form
9280
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
@@ -97,7 +85,7 @@ public function execute()
9785
);
9886
$resultPage->getConfig()->getTitle()->prepend(__('Tags'));
9987
$resultPage->getConfig()->getTitle()
100-
->prepend($model->getId() ? $model->getTitle() : __('New Tag'));
88+
->prepend($tag->getId() ? $tag->getTagTitle() : __('New Tag'));
10189

10290
return $resultPage;
10391
}

Controller/Adminhtml/Tag/Grid.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public function __construct(
4141
*/
4242
public function execute()
4343
{
44-
$tag = $this->_initTag(true);
44+
$tag = $this->_initTag();
4545
if (!$tag) {
4646
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
4747
$resultRedirect = $this->resultRedirectFactory->create();

Controller/Adminhtml/Tag/Save.php

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,18 @@ public function execute()
6161
return $resultRedirect->setPath('*/*/');
6262
}
6363
}
64-
6564
$model->setData($data);
65+
if (isset($data['tag_products'])
66+
&& is_string($data['tag_products'])) {
67+
$products = json_decode($data['tag_products'], true);
68+
$model->setPostedProducts($products);
69+
}
70+
$this->_eventManager->dispatch(
71+
'lof_producttags_prepare_save',
72+
['tag' => $model, 'request' => $this->getRequest()]
73+
);
74+
$products = $model->getPostedProducts();
75+
6676
try{
6777
$model->save($model);
6878
$this->messageManager->addSuccessMessage(__('You saved the tag.'));
@@ -75,16 +85,14 @@ public function execute()
7585
}
7686

7787
$this->dataPersistor->set('lof_productags_tag', $data);
78-
$this->dataPersistor->set('lof_producttags_product', $data);
79-
$this->dataPersistor->set('lof_producttags_store', $data);
8088
return $resultRedirect->setPath('*/*/edit', ['tag_id' => $id]);
8189
}
8290
return $resultRedirect->setPath('*/*/');
8391
}
8492
private function processBlockReturn($model, $data, $resultRedirect)
8593
{
8694
$redirect = $data['back'] ?? 'close';
87-
95+
// $position = $model->getProductsPosition();
8896
if ($redirect ==='continue') {
8997
$resultRedirect->setPath('*/*/edit', ['tag_id' => $model->getId()]);
9098
} else if ($redirect === 'close') {
@@ -94,12 +102,11 @@ private function processBlockReturn($model, $data, $resultRedirect)
94102
$duplicateModel->setId(null);
95103
$duplicateModel->setIdentifier($data['identifier'] . '-' . uniqid());
96104
$duplicateModel->setIsActive(Tag::STATUS_DISABLED);
105+
// $duplicateModel->setProductPosition($position);
97106
$this->tagRepository->save($duplicateModel);
98107
$id = $duplicateModel->getId();
99108
$this->messageManager->addSuccessMessage(__('You duplicated the tag.'));
100109
$this->dataPersistor->set('lof_productags_tag', $data);
101-
$this->dataPersistor->set('lof_producttags_product', $data);
102-
$this->dataPersistor->set('lof_producttags_store', $data);
103110
$resultRedirect->setPath('*/*/edit', ['tag_id' => $id]);
104111
}
105112
return $resultRedirect;

Model/ResourceModel/Tag.php

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,151 @@
11
<?php
22
namespace Lof\ProductTags\Model\ResourceModel;
3+
use Magento\Framework\Model\AbstractModel;
4+
use Magento\Catalog\Model\Indexer\Category\Product\Processor;
5+
use Magento\Framework\DataObject;
6+
use Magento\Framework\EntityManager\EntityManager;
7+
use Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface;
38

49
class Tag extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
510
{
11+
protected $_tagProductTable = '';
12+
613
protected function _construct()
714
{
815
$this->_init('lof_producttags_tag', 'tag_id');
916
}
17+
18+
/**
19+
* Process page data after saving
20+
*
21+
* @param AbstractModel $object
22+
* @return $this
23+
* @throws LocalizedException
24+
*/
25+
protected function _afterSave(AbstractModel $object)
26+
{
27+
$this->_saveTagProducts($object);
28+
return parent::_afterSave($object);
29+
}
30+
31+
public function getTagProductTable()
32+
{
33+
if (!$this->_tagProductTable) {
34+
$this->_tagProductTable = $this->getTable('lof_producttags_product');
35+
}
36+
return $this->_tagProductTable;
37+
}
38+
39+
protected function _saveTagProducts($tag)
40+
{
41+
$tag->setIsChangedProductList(false);
42+
$id = $tag->getId();
43+
44+
/**
45+
* new tag-product relationships
46+
*/
47+
$products = $tag->getPostedProducts();
48+
/**
49+
* Example re-save category
50+
*/
51+
if ($products === null) {
52+
return $this;
53+
}
54+
55+
/**
56+
* old category-product relationships
57+
*/
58+
$oldProducts = $tag->getProductsPosition();
59+
60+
$insert = array_diff_key($products, $oldProducts);
61+
$delete = array_diff_key($oldProducts, $products);
62+
63+
/**
64+
* Find product ids which are presented in both arrays
65+
* and saved before (check $oldProducts array)
66+
*/
67+
$update = array_intersect_key($products, $oldProducts);
68+
$update = array_diff_assoc($update, $oldProducts);
69+
70+
$connection = $this->getConnection();
71+
72+
/**
73+
* Delete products from tag
74+
*/
75+
if (!empty($delete)) {
76+
$cond = ['product_id IN(?)' => array_keys($delete), 'tag_id=?' => $id];
77+
$connection->delete($this->getTagProductTable(), $cond);
78+
}
79+
80+
/**
81+
* Add products to tag
82+
*/
83+
if (!empty($insert)) {
84+
$data = [];
85+
foreach ($insert as $productId => $position) {
86+
$data[] = [
87+
'tag_id' => (int)$id,
88+
'product_id' => (int)$productId,
89+
'position' => (int)$position,
90+
];
91+
}
92+
$connection->insertMultiple($this->getTagProductTable(), $data);
93+
}
94+
95+
/**
96+
* Update product positions in category
97+
*/
98+
if (!empty($update)) {
99+
$newPositions = [];
100+
foreach ($update as $productId => $position) {
101+
$delta = $position - $oldProducts[$productId];
102+
if (!isset($newPositions[$delta])) {
103+
$newPositions[$delta] = [];
104+
}
105+
$newPositions[$delta][] = $productId;
106+
}
107+
108+
foreach ($newPositions as $delta => $productIds) {
109+
$bind = ['position' => new \Zend_Db_Expr("position + ({$delta})")];
110+
$where = ['tag_id = ?' => (int)$id, 'product_id IN (?)' => $productIds];
111+
$connection->update($this->getTagProductTable(), $bind, $where);
112+
}
113+
}
114+
if (!empty($insert) || !empty($delete)) {
115+
$productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
116+
$tag->setChangedProductIds($productIds);
117+
}
118+
119+
if (!empty($insert) || !empty($update) || !empty($delete)) {
120+
$tag->setIsChangedProductList(true);
121+
122+
/**
123+
* Setting affected products to tag for third party engine index refresh
124+
*/
125+
$productIds = array_keys($insert + $delete + $update);
126+
$tag->setAffectedProductIds($productIds);
127+
}
128+
129+
return $this;
130+
}
131+
/**
132+
* Get positions of associated to tag products
133+
*
134+
* @param \Lof\ProductTags\Model\Tag $tag
135+
* @return array
136+
*/
137+
public function getProductsPosition($tag)
138+
{
139+
$select = $this->getConnection()->select()->from(
140+
$this->getTagProductTable(),
141+
['product_id', 'position']
142+
)->where(
143+
"{$this->getTable('lof_producttags_product')}.tag_id = ?",
144+
(int)$tag->getId()
145+
);
146+
147+
$bind = ['tag_id' => (int)$tag->getId()];
148+
149+
return $this->getConnection()->fetchPairs($select, $bind);
150+
}
10151
}

Model/Tag.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,6 @@ public function getProductsPosition()
6060
}
6161

6262
public function getRelatedReadonly(){
63-
return true;
63+
return false;
6464
}
6565
}

Model/Tag/Source/IsActive.php

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,11 @@ class IsActive implements OptionSourceInterface
1717
*/
1818
protected $producttags;
1919

20-
/**
21-
* Constructor
22-
*
23-
* @param \Magento\Cms\Model\Block $cmsBlock
24-
*/
2520
public function __construct(\Lof\ProductTags\Model\Tag $producttags)
2621
{
2722
$this->producttags = $producttags;
2823
}
2924

30-
/**
31-
* Get options
32-
*
33-
* @return array
34-
*/
3525
public function toOptionArray()
3626
{
3727
$availableOptions = $this->producttags->getAvailableStatuses();

view/adminhtml/templates/lof_producttags/tag/edit/assign_products.phtml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ $gridJsObjectName = $blockGrid->getJsObjectName();
77
<script type="text/x-magento-init">
88
{
99
"*": {
10-
"Lof_ProductTags/tag/edit/assign-products": {
10+
"Lof_ProductTags/js/tag/edit/assign-products": {
1111
"selectedProducts": <?= /* @escapeNotVerified */ $block->getProductsJson() ?>,
1212
"gridJsObjectName": <?= /* @escapeNotVerified */ '"' . $gridJsObjectName . '"' ?: '{}' ?>
1313
}

0 commit comments

Comments
 (0)