I have used the following technique to add a new button to an existing grid.

The same technique could be used to remove or reorder buttons too.

Grid containers extend Magento\Backend\Block\Widget\Container. During _prepareLayout, any buttons that have been added to the grid get pushed to a toolbar model ($this->toolbar->pushButtons($this, $this->buttonList);).

Because the pushButtons() method is public we can use it to “plugin” to and modify the buttons array. Firstly we must declare our plugin.

In app/code/[codePool]/[Vendor]/[ModuleName]/etc/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Backend\Block\Widget\Button\Toolbar">
        <plugin name="upload" type="[Vendor]\[ModuleName]\Plugin\Toolbar" sortOrder="10"/>
    </type>
</config>

Next we must write our plugin implementation.

In app/code/[codePool]/[Vendor]/[ModuleName]/Plugin/Toolbar.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

namespace [Vendor]\[ModuleName]\Plugin;

use Magento\Backend\Block\Widget\Button\ButtonList;
use Magento\Backend\Block\Widget\Button\Toolbar as ToolbarContext;
use Magento\Framework\View\Element\AbstractBlock;

class Toolbar
{
    public function beforePushButtons(
        ToolbarContext $toolbar,
        AbstractBlock $context,
        ButtonList $buttonList
    ) {
        if ($context instanceof \Magento\UrlRewrite\Block\GridContainer) {
            $buttonList->add('upload', [
                'label' => __('Upload'),
                'onclick' => 'setLocation(\'' .$context->getUrl('*/*/upload'). '\')',
                'class' => 'upload'
            ]);
        }

        return [$context, $buttonList];
    }
}

We use the “before” plugin type (Line 11) to manipulate the button list before it is pushed to the toolbar.

Of course, this is just a generic plugin for the toolbar so the first thing we need to do is check that the block type is the block we wish to add our button to (Line 16). In the above case, I want to add a button to the UrlRewrite grid container.

You can use the $buttonList to just add a button now in the regular way.

Finally, you must return the original arguments.

  • magento2

Like this post? Share it :)


Related Posts

Back