0

I have created custom button on Adminhtml Product edit page and it's showing fine. When I hit the button it's redirecting to Product List page and throwing Error.

Error: Invalid product id. Should be numeric value greater than 0

enter image description here

for this I have written below code.

root/vendor/magento/module-catalog/view/adminhtml/ui_component/product_form.xml

<item name="buttons" xsi:type="array">        
            <item name="custom" xsi:type="array">
                <item name="name" xsi:type="string">Custom</item>
                <item name="label" xsi:type="string" translate="true">Custom</item>
                <item name="class" xsi:type="string">custom</item>
                <item name="url" xsi:type="string">*/*/custom</item>
            </item>
        </item>

root/vendor/magento/module-catalog/Controller/adminhtml/Product/Edit/Custom.php

<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Catalog\Controller\Adminhtml\Product;

class Custom extends \Magento\Catalog\Controller\Adminhtml\Product
{
    /**
     * Array of actions which can be processed without secret key validation
     *
     * @var array
     */
    protected $_publicActions = ['edit'];

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Catalog\Controller\Adminhtml\Product\Builder $productBuilder
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Catalog\Controller\Adminhtml\Product\Builder $productBuilder,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        parent::__construct($context, $productBuilder);
        $this->resultPageFactory = $resultPageFactory;
    }

    /**
     * Product edit form
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {

        /** @var \Magento\Store\Model\StoreManagerInterface $storeManager */
        $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $storeId = (int) $this->getRequest()->getParam('store', 0);
        $store = $storeManager->getStore($storeId);
        $storeManager->setCurrentStore($store->getCode());
        $productId = (int) $this->getRequest()->getParam('id');
        $product = $this->productBuilder->build($this->getRequest());

        file_put_contents('product.txt', print_r($productId,true), FILE_APPEND);

        if (($productId && !$product->getEntityId())) {
            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $this->messageManager->addError(__('This product doesn\'t exist.'));
            return $resultRedirect->setPath('catalog/*/');
        } else if ($productId === 0) {
            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $this->messageManager->addError(__('Invalid product id. Should be numeric value greater than 0'));
            return $resultRedirect->setPath('catalog/*/');
        }

        $this->_eventManager->dispatch('catalog_product_edit_action', ['product' => $product]);

        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        $resultPage->addHandle('catalog_product_' . $product->getTypeId());
        $resultPage->setActiveMenu('Magento_Catalog::catalog_products');
        $resultPage->getConfig()->getTitle()->prepend(__('Products'));
        $resultPage->getConfig()->getTitle()->prepend($product->getName());

        if (!$this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->isSingleStoreMode()
            &&
            ($switchBlock = $resultPage->getLayout()->getBlock('store_switcher'))
        ) {
            $switchBlock->setDefaultStoreName(__('Default Values'))
                ->setWebsiteIds($product->getWebsiteIds())
                ->setSwitchUrl(
                    $this->getUrl(
                        'catalog/*/*',
                        ['_current' => true, 'active_tab' => null, 'tab' => null, 'store' => null]
                    )
                );
        }

        $block = $resultPage->getLayout()->getBlock('catalog.wysiwyg.js');
        if ($block) {
            $block->setStoreId($product->getStoreId());
        }

        return $resultPage;
    }
}

and button showing in product edit page.

enter image description here

When I hit the button it's redirecting to Product List page and throwing error. Error: Invalid product id. Should be numeric value greater than 0

When I hit the button I want to get the product id and after post back it's in same page no need to redirect list page.

Help me on this.

1 Answer 1

1

Check following code.

VendorName=SR , ModuleName=StackExchange

UI_Component form config [SR/StackExchange/view/adminhtml/ui_component/product_form.xml]


<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
       <item name="buttons" xsi:type="array">
            <item name="custom" xsi:type="string">SR\StackExchange\Block\Adminhtml\Product\Edit\Button\Custom
        </item>
    </argument>
</form>


Button class [SR/StackExchange/Block/Adminhtml/Product/Edit/Button/Custom.php]



namespace SR\StackExchange\Block\Adminhtml\Product\Edit\Button;

class Custom extends \Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic
{
    /**
     * {@inheritdoc}
     */
    public function getButtonData()
    {
        if($this->getProduct()->getId()) {
            $store = $this->context->getRequestParam('store');
            if(!isset($store)) {
                $store = 0;
            }

            $params = [
                'id' => $this->getProduct()->getId(),
                'store' => $store
            ];
            $customUrl = $this->getUrl('stackexchange/stackexchange/custom', $params);
            return [
                'label' => __('Custom Button'),
                'on_click' => sprintf("location.href = '%s';", $customUrl),
                'class' => 'action-secondary',
                'sort_order' => 10
            ];
        }
    }
}

Controller [SR/StackExchange/Controller/Adminhtml/Stackexchange/Custom.php]



namespace SR\StackExchange\Controller\Adminhtml\Stackexchange;

class Custom extends \Magento\Catalog\Controller\Adminhtml\Product
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * Save constructor.
     *
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Catalog\Controller\Adminhtml\Product\Builder $productBuilder
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Catalog\Controller\Adminhtml\Product\Builder $productBuilder,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $productBuilder);
    }

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $productId = (int) $this->getRequest()->getParam('id');
        $store = $this->getRequest()->getParam('store');
        $product = $this->productRepository->getById($productId);

        $resultRedirect->setPath(
            'catalog/product/edit',
            ['id' => $productId, 'store' => $store,'_current' => true, 'set' => $product->getAttributeSetId()]
        );

        return $resultRedirect;
    }
}

And Admin router looks like


#SR/StackExchange/etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="stackexchange" frontName="stackexchange">
            <module name="SR_StackExchange" before="Magento_Adminhtml" />
        </route>
    </router>
</config>


0

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.