Magento 2 create button to product and category front page from product and category edit admin view

Magento 2 create button to product and category front page from product and category edit admin view

thumbnail

In this topic, we will show you how you can add a button on the product and category edit page in the admin panel to see the product and category view on the front of the application. This can be helpful if someone will add or edit products and see in a fast way how it looks without opening a new tab, go to the domain, search for product or category what you want to see and click. Hmm.. this is not very optimal. So, let’s start.

At the beginning you can learn a tutorial – how to create a module in Magento 2.

1. Product view

Step 1. Creating Adminhtml Block.

At first, you should create Adminhtml Block where is included whole logic for button data like placement, action on click with proper URL, label, HTML attributes.

The file should be like this example path:

app/code/[your_module]/CatalogView/Block/Adminhtml/Product/Edit/Button/View.php

 

The code inside:

<?php

namespace PandaGroup\CatalogView\Block\Adminhtml\Product\Edit\Button;

use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic;

use Magento\Catalog\Model\Product\Url;

use Magento\Framework\Registry;

use Magento\Framework\View\Element\UiComponent\Context;

use Magento\Store\Model\StoreManagerInterface;

/**

* Class View

* @package PandaGroup\CatalogView\Block\Adminhtml\Product\Edit\Button

*/

class View extends Generic

{

   /**

    * @var Url $productUrl

    */

   private $productUrl;

   /**

    * @var StoreManagerInterface $storeManager

    */

   private $storeManager;

   /**

    * View constructor.

    * @param Context $context

    * @param Registry $registry

    * @param Url $productUrl

    * @param StoreManagerInterface $storeManager

    */

   public function __construct(

       Context $context,

       Registry $registry,

       Url $productUrl,

       StoreManagerInterface $storeManager

   ) {

       parent::__construct($context, $registry);

       $this->productUrl = $productUrl;

       $this->storeManager = $storeManager;

   }

   /**

    * @return array

    * @throws \Magento\Framework\Exception\NoSuchEntityException

    */

   public function getButtonData()

   {

       if ($this->getProduct()->isReadonly()) {

           return [];

       }

       $product = $this->getProduct()->setStoreId($this->getCurrentStoreId());

       return [

               ‘label’ => __(‘Product View’),

               ‘on_click’ => sprintf(“window.open(‘%s’, ‘_blank’);”, $this->productUrl->getProductUrl($product)),

               ‘class’ => ‘view action-secondary’,

               ‘sort_order’ => 10

       ];

   }

   /**

    * @return int

    * @throws \Magento\Framework\Exception\NoSuchEntityException

    */

   private function getCurrentStoreId(): int

   {

       $currentStoreId = (int)$this->storeManager->getStore()->getId();

       if ($currentStoreId === \Magento\Store\Model\Store::DEFAULT_STORE_ID) {

           $currentStoreId = $this->storeManager->getDefaultStoreView()->getId();

       }

       return $currentStoreId;

   }

}

What we are doing here is injecting Product Url class to create URL to front product view, and StoreManagerInterface to get current store ID, but not the admin panel ID, because if we get the product with admin ID, the URL will generate a non-existent link to admin product view. It’s important.

 

Step 2. Create ui_component in view of product form.

The file should be like this example path:

app/code/[your_module]/view/adminhtml/ui_component/product_form.xml

 

The code inside:

<?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”>

   <settings>

       <buttons>

           <button name=”product_view” class=”PandaGroup\CatalogView\Block\Adminhtml\Product\Edit\Button\View”/>

       </buttons>

   </settings>

</form>

In this file, we are telling Magento to add a block to the form of a product edit.

 

2. Category view

Step 1. Creating Adminhtml Block

Creating a category view is analogous to the above method of product view.

The file should be like this example path:

app/code/[your_module]/CatalogView/Block/Adminhtml/Category/Edit/Button/View.php

 

The code inside:

<?php

namespace PandaGroup\CatalogView\Block\Adminhtml\Category\Edit\Button;

use Magento\Catalog\Block\Adminhtml\Category\AbstractCategory;

use Magento\Framework\Registry;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

use Magento\Store\Model\StoreManagerInterface;

use Magento\Catalog\Model\CategoryFactory;

use Magento\Backend\Block\Template\Context;

use Magento\Catalog\Model\ResourceModel\Category\Tree as CategoryTree;

/**

* Class View

* @package PandaGroup\CatalogView\Block\Adminhtml\Category\Edit\Button

*/

class View extends AbstractCategory implements ButtonProviderInterface

{

   /**

    * @var StoreManagerInterface

    */

   private $storeManager;

   /**

    * View constructor.

    * @param Context $context

    * @param CategoryTree $categoryTree

    * @param Registry $registry

    * @param CategoryFactory $categoryFactory

    * @param array $data

    * @param StoreManagerInterface $storeManager

    */

   public function __construct(

       Context $context,

       CategoryTree $categoryTree,

       Registry $registry,

       CategoryFactory $categoryFactory,

       array $data = [],

       StoreManagerInterface $storeManager

   ) {

       parent::__construct($context, $categoryTree, $registry, $categoryFactory, $data);

       $this->storeManager = $storeManager;

   }

   /**

    * Category view button

    *

    * @return array

    * @throws \Magento\Framework\Exception\NoSuchEntityException

    */

   public function getButtonData()

   {

       /** @var \Magento\Catalog\Model\Category $category */

       $category = $this->getCategory();

       $categoryId = $category->getId();

       $category->setStoreId($this->getCurrentStoreId());

       $categoryUrl = $category->getUrl();

 

       if ($categoryId && !in_array($categoryId, $this->getRootIds()) && $category->isDeleteable()) {

           return [

               ‘id’ => ”,

               ‘label’ => __(‘Category View’),

               ‘class’ => ‘view action-secondary’,

               ‘on_click’ =>  sprintf(“window.open(‘%s’, ‘_blank’);”, $categoryUrl),

               ‘sort_order’ => 10

           ];

       }

       return [];

   }

   /**

    * @return int

    * @throws \Magento\Framework\Exception\NoSuchEntityException

    */

   private function getCurrentStoreId(): int

   {

       $currentStoreId = (int)$this->storeManager->getStore()->getId();

       if ($currentStoreId === \Magento\Store\Model\Store::DEFAULT_STORE_ID) {

           $currentStoreId = $this->storeManager->getDefaultStoreView()->getId();

       }

       return $currentStoreId;

   }

}

The code above is analogous to the product with one difference, there is no category URL service, but we are getting category and set proper id and get a URL from its model. Otherwise, the category model will generate a non-existent link to the admin category view.

 

Step 2. Create ui_component in view of product form.

The file should be like this example path:

app/code/[your_module]/view/adminhtml/ui_component/product_form.xml

 

The code inside:

<?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”>

   <settings>

       <buttons>

           <button name=”product_view” class=”PandaGroup\CatalogView\Block\Adminhtml\Product\Edit\Button\View”/>

       </buttons>

   </settings>

</form>

 

In this file, we are telling Magento to add the block to the form of category edit.

And that’s all. Compile your project, clear cache and check if everything works. 

Remember! If you copy and paste these code examples – change PandaGroup to your name 👀.

...