Magento2 Add Tab To Customer Edit Page In Admin Panel

Considering that you have the basic knowledge of module creation, we will be continuing to review the code of only those file which are needed for adding tab.
Create a file under view\adminhtml\layout\customer_index_edit.xml and the following code to add a tab to customer edit page:-

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceBlock name="customer_form">
                 <block class="W3solver\Invoice\Block\Adminhtml\Customer\Edit\Tab\Invoice" name="admin.customer.invoice.tab"/>
        </referenceBlock>
    </body>
</page>

You then need to add a tab wrapper for invoice so that URL can be associated with the tab(create the file under block folder and follow the path as provided in class in xml, in our case it is Block\Adminhtml\Customer\Edit\Tab\Invoice.php):-

namespace W3solver\Invoice\Block\Adminhtml\Customer\Edit\Tab;

use Magento\Backend\Block\Template\Context;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Framework\Registry;
use Magento\Ui\Component\Layout\Tabs\TabWrapper;

class Invoice extends TabWrapper {

    protected $_coreRegistry;

    public function __construct(
    \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    public function getCustomerId() {
        return $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
    }

    public function getTabLabel() {
        return __("Invoice");
    }

    public function getTabTitle() {
        return __("Invoice");
    }

    public function canShowTab() {
        if ($this->getCustomerId()) {
            return true;
        }
        return false;
    }

    public function isHidden() {
        if ($this->getCustomerId()) {
            return false;
        }
        return true;
    }

    public function getTabClass() {
        return 'invoice-details';
    }

    public function getTabUrl() {
        return $this->getUrl('invoice/index/view', ['_current' => true]);
    }

    public function isAjaxLoaded() {
        return true;
    }

}

For url to work a custom controller needs to be added (Controller\Adminhtml\Index\view.php)

namespace W3solver\Invoice\Controller\Adminhtml\Index;

class View extends \Magento\Customer\Controller\Adminhtml\Index {

    public function execute() {

        $this->initCurrentCustomer();
        $resultLayout = $this->resultLayoutFactory->create();
        return $resultLayout;
    }

}
magento2_customer_custom_tab

Magento 2 Customer Custom Tab

This will show a tab in admin panel under customer edit page as shown in above image, to add a grid to this tab look for the next blog.

Leave a Comment.