4

I need to create a custom "admin" block and display it on any admin "product edit" page in Magento 2.1.x.

But I also want to be able to display it on any admin page, if I need.

Which block classes do I have to extend ? What is the folder structure for admin blocks ?

Any help would be appreciated!

1 Answer 1

10

Traditional location for admin blocks is (Example):

app/code/YourVendor/YourModule/Block/Adminhtml/...

If you'd like to use block with phtml template you'd like to extend

\Magento\Framework\View\Element\Template

It is valid both for backend and frontend blocks

The template for your block should be located under:

app/code/YourVendor/YourModule/view/<area>/templates/...

Where area can be:

  • adminhtml for backend
  • frontend for frontend
  • base for both

Then you can add the block to any page using layout. I.e. for product edit page the layout file should be:

app/code/YourVendor/YourModule/view/adminhtml/layout/catalog_product_edit.xml

The example content of such layout:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="YourVendor\YourModule\Block\Adminhtml\Example" name="example_block_name" template="YourVendor_YourModule::example.phtml"/>
        </referenceContainer>
    </body>
</page>

Use referenceContainer or referenceBlock name to define where exactly you want your block to be displayed on a page. Use layout name (that is based on MCA or simply URL) to define which page will be updated with your block. default.xml layout is included on all pages.

1
  • maybe extend \Magento\Backend\Block\Template
    – Ian at SSU
    Aug 30, 2021 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.