3

Di.xml

<type name="Magento\Catalog\Controller\Adminhtml\Category\Save">
        <plugin name="mymodule" type="Module\Name\Plugin\Controller\Adminhtml\Category\Save"/>
</type>

Save.php

<?php 
namespace Module\Name\Plugin\Controller\Adminhtml\Category;

use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory; 
use \Magento\Framework\View\Element\UiComponent\ContextInterface;

class Save {

    protected $resultRedirect;

    protected $resultRawFactory;

    protected $resultJsonFactory;

    protected $layoutFactory;

    protected $stringToBoolInputs = [
        'custom_use_parent_settings',
        'custom_apply_to_products',
        'is_active',
        'include_in_menu',
        'is_anchor',
        'use_default' => ['url_key'],
        'use_config' => ['available_sort_by', 'filter_price_range', 'default_sort_by']
    ];

    private $storeManager;


    public function __construct(
        ContextInterface $context,
        \Magento\Framework\Controller\ResultFactory $result,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\View\LayoutFactory $layoutFactory,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->resultRawFactory = $resultRawFactory;
        $this->resultRedirect = $result;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->layoutFactory = $layoutFactory;
        $this->storeManager = $storeManager;
    }

    public function afterExecute()
    {


        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/category_save.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$logger->info("Info");


        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */


        $resultRedirect = $this->resultRedirectFactory->create();
        /*$resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);*/

        $category = $this->_initCategory();

        if (!$category) {
            return $resultRedirect->setPath('catalog/*/', ['_current' => true, 'id' => null]);
        }

        $data['general'] = $this->getRequest()->getPostValue();
        $categoryPostData = $data['general'];

        $isNewCategory = !isset($categoryPostData['entity_id']);
        $categoryPostData = $this->stringToBoolConverting($categoryPostData);
        $categoryPostData = $this->imagePreprocessing($categoryPostData);
        $categoryPostData = $this->dateTimePreprocessing($category, $categoryPostData);
        $storeId = isset($categoryPostData['store_id']) ? $categoryPostData['store_id'] : null;
        $store = $this->storeManager->getStore($storeId);
        $this->storeManager->setCurrentStore($store->getCode());
        $parentId = isset($categoryPostData['parent']) ? $categoryPostData['parent'] : null;
        if ($categoryPostData) {
            $category->addData($this->_filterCategoryPostData($categoryPostData));
            if ($isNewCategory) {
                $parentCategory = $this->getParentCategory($parentId, $storeId);
                $category->setPath($parentCategory->getPath());
                $category->setParentId($parentCategory->getId());
            }

            /**
             * Process "Use Config Settings" checkboxes
             */

            $useConfig = [];
            if (isset($categoryPostData['use_config']) && !empty($categoryPostData['use_config'])) {
                foreach ($categoryPostData['use_config'] as $attributeCode => $attributeValue) {
                    if ($attributeValue) {
                        $useConfig[] = $attributeCode;
                        $category->setData($attributeCode, null);
                    }
                }
            }

            $category->setAttributeSetId($category->getDefaultAttributeSetId());

            if (isset($categoryPostData['category_products'])
                && is_string($categoryPostData['category_products'])
                && !$category->getProductsReadonly()
            ) {
                $products = json_decode($categoryPostData['category_products'], true);
                $category->setPostedProducts($products);
            }
            $this->_eventManager->dispatch(
                'catalog_category_prepare_save',
                ['category' => $category, 'request' => $this->getRequest()]
            );

            /**
             * Check "Use Default Value" checkboxes values
             */
            if (isset($categoryPostData['use_default']) && !empty($categoryPostData['use_default'])) {
                foreach ($categoryPostData['use_default'] as $attributeCode => $attributeValue) {
                    if ($attributeValue) {
                        $category->setData($attributeCode, null);
                    }
                }
            }

            /**
             * Proceed with $_POST['use_config']
             * set into category model for processing through validation
             */
            $category->setData('use_post_data_config', $useConfig);

            try {
                $categoryResource = $category->getResource();
                if ($category->hasCustomDesignTo()) {
                    $categoryResource->getAttribute('custom_design_from')->setMaxValue($category->getCustomDesignTo());
                }

                $validate = $category->validate();
                if ($validate !== true) {
                    foreach ($validate as $code => $error) {
                        if ($error === true) {
                            $attribute = $categoryResource->getAttribute($code)->getFrontend()->getLabel();
                            throw new \Magento\Framework\Exception\LocalizedException(
                                __('Attribute "%1" is required.', $attribute)
                            );
                        } else {
                            throw new \Exception($error);
                        }
                    }
                }

                $category->unsetData('use_post_data_config');

                $category->save();
                $this->messageManager->addSuccess(__('You saved the category.'));
            } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
                $this->messageManager->addError($e->getMessage());
                $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
                $this->_getSession()->setCategoryData($categoryPostData);
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
                $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
                $this->_getSession()->setCategoryData($categoryPostData);
            } catch (\Exception $e) {
                $this->messageManager->addError(__('Something went wrong while saving the category.'.$e->getMessage()));
                $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
                $this->_getSession()->setCategoryData($categoryPostData);
            }
        }
}
}

Getting this errors

Exception #0 (Exception): Notice: Undefined property: Module\Name\Plugin\Controller\Adminhtml\Category\Save::$resultRedirectFactory in 



also getting an error near this line

$category = $thianyonetCategory();

If any one idea please share and help me as soon as

  • 1
    your approach is technically wrong what you want will not be done in after plugin. you have to change it to around plugin or use preference to rewrite this class.second option is better in your case. – Hassan Ali Shahzad Oct 17 '18 at 7:50
-1

You're trying to use a class property ($resultRedirectFactory) which doesn't exist in your class (not declared).

To make this working, you have to change in your class:

1) from protected $resultRedirect; to protected $resultRedirectFactory;

2) from

public function __construct(
    ...
    \Magento\Framework\Controller\ResultFactory $result,
    ...
) {
    ...
    $this->resultRedirect = $result;
    ...
}
...

to

public function __construct(
    ...
    \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
    ...
) {
    ...
    $this->resultRedirectFactory = $resultRedirectFactory;
    ...
}
...
  • getting this error for this : parent::__construct($context); Fatal error: Uncaught Error: Cannot access parent:: when current class scope has no parent in – Jimit Bhavsar Oct 17 '18 at 5:59
  • @Bhavsar Hey, your class should extend abstract admin panel action in order to work – Nikita Abrashnev Oct 17 '18 at 8:43
  • ` Save extends \Magento\Backend\App\Action` – Nikita Abrashnev Oct 17 '18 at 9:04
-1

You have to changes

$resultRedirect = $this->resultRedirectFactory->create();

to

$resultRedirect = $this->resultRedirect->create();

see your _construct function, You are to injected as

\Magento\Framework\Controller\ResultFactory $result

and $this->resultRedirect = $result;

has result factory.

Also, Also, you have to remove parent::__construct($context);

  • getting this error for this : parent::__construct($context); Fatal error: Uncaught Error: Cannot access parent:: when current class scope has no parent in – Jimit Bhavsar Oct 17 '18 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.