Skip to main content

How to add custom button in category form admin ?

Here we will learn how to add button on category page.

The category form is generated via ui-component, the ui-component name for category form is view/adminhtml/ui_component/category_form.xml

You need to create a file with the same name and path in your own module:
Create same file [Namespace]/[Module]/view/adminhtml/ui_component/category_form.xml and copy following content:


<?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="exercise" xsi:type="string">AGM\Exercise\Block\Adminhtml\Category\Edit\ExerciseButton</item>

        </item>

 </argument>

</form>

Then create class [Namespace]\[Module]\Block\Adminhtml\Category\Edit\ExerciseButon

<?php
namespace AGM\Exercise\Block\Adminhtml\Category\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
use Magento\Catalog\Block\Adminhtml\Category\AbstractCategory;

class ExerciseButton extends AbstractCategory implements ButtonProviderInterface
{
    protected $_url;
    public function __construct(
  \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\Tree $categoryTree,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Framework\Url $url,
  array $data = []
    ) {
        $this->_url = $url;
  $this->dataHelper = $dataHelper;
  parent::__construct($context,$categoryTree,$registry,$categoryFactory,$data);
    }

    public function getButtonData()
    {
  return [
   'id' => 'exercise',
   'label' => __('Exercise'),
   'on_click'  => 'window.open(\'' . $this->getExceriseUrl() . '\')',
   'class' => 'action- scalable',
   'sort_order' => 15
  ];
        return [];
    }
}


Your ui component file should be merged with the main file and your buttons should appear among the other buttons. Hope this helps you.

Cheers!

Comments