Magento 2: Add new button on Category Edit Page in Admin Panel

For this example we will assume you have a custom module. Let's call it Namespace_Module.

Now, create files as below:

Namespace_Module\view\adminhtml\ui_component\category_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* @author Reena Parekh <reena1.parekh@gmail.com>
*/
-->
<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="button-unique-identifier-here" xsi:type="string">
Namespace\Module\Block\Adminhtml\Category\Edit\Button\AssignButton
</item>
</item>
</argument>
</form>


Namespace_Module\Block\Adminhtml\Category\Edit\Button\AssignButton.php
<?php
<!--
/**
* @author Reena Parekh <reena1.parekh@gmail.com>
*/
-->
namespace Namespace\Module\Block\Adminhtml\Category\Edit\Button;
use Magento\Catalog\Block\Adminhtml\Category\AbstractCategory;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class AssignButton extends AbstractCategory implements ButtonProviderInterface
{
/**
* Assign button
*
* @return array
*/
public function getButtonData()
{
$category = $this->getCategory();
$message = __('Are you sure you want to submit the data ?');
if (!$category->isReadonly() && $this->hasStoreRootCategory()) {
return [
'label' => __('Assign'),
'class' => 'assign primary',
'on_click' => "confirmSetLocation('{$message}', '{$this->getCustomUrl()}')",
'sort_order' => 30,
];
}
return [];
}
/**
* URL getter
*
* @return string
*/
public function getCustomUrl()
{
return $this->getUrl('mymodule/category/assign', ['category_id' => $this->getCategory()->getId()]);
}
}


Namespace_Module\Controller\Adminhtml\Category\Assign.php
<?php
/**
* @author Reena Parekh <reena1.parekh@gmail.com>
*/
namespace Namespace\Module\Controller\Adminhtml\Category;
/**
* Class Assign
*/
class Assign extends \Magento\Catalog\Controller\Adminhtml\Category
{
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
if ($categoryId = $this->getRequest()->getParam('category_id')) {
//Add code related to whatever you want to do on button click here.
$this->messageManager->addSuccess(__('Operation performed successfully.'));
$resultRedirect->setPath('catalog/category/edit', ['id' => $categoryId, '_current' => true]);
}
return $resultRedirect;
}
}
view raw Assign.php hosted with ❤ by GitHub


Voila !! That's it. Now, clear all caches and check the category page in admin panel. There will be a new button called "Assign".

Comments

Popular posts from this blog

SEO for your Press Releases [Updated 2025 list]

XDebug - PHPStorm - Mac: How to configure Xdebug with PHPStorm on Mac OS and PHP 7.3