Monday, 26 March 2018

Add Custom JS on Magento 2 admin

I was creating a new extension that involves customization on Magento 2 Admin panel. As part of it, I needed to add custom javascript on the admin panel.

There are two ways you can add your custom JS on admin panel.

  • Including it with blocks
  • Including it in head and loading by require js

Including it with Blocks

create folder structure like this view/adminhtml/layout/
create new file default.xml inside it.

<page xmlns:xsi="" xsi:nonamespaceschemalocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
         <referencecontainer name="js">
            <block class="Magento\Backend\Block\Template" name="admincustomjs" template="Your_Modulename::system/config/additional_script.phtml">

If you want to include your script in footer just replace the referencecontainer name="footer"

In additional_script.phtml you can include your custom script like this.
<script type="text/javascript">
        function($) {
            $(function() {
              console.log('custom script included successfully');

If you see page source of the system config page or any other page in admin panel, you can see there are few custom scripts included by Magento Just above the Footer tag.

Including it in head and loading by require js

When using this method don't use default.xml to include your script in <head> tag. This will load your script BEFORE the main require js is loaded and it will create a JS error.

create folder structure like this  view/adminhtml/layout/adminhtml_system_config_edit.xml

You can change the xml file name inside layout folder as per your admin page action. EG: customer_index_edit.xml

<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<link src="Your_Modulename::js/custom_require.js"/>

You need to place the custom_require.js inside view/adminhtml/web/js/ 
In custom_require.js use require method to include your custom javascript.

Create custom_system_config.js file inside view/adminhtml/web/
place your custom javascript in this file

function($) {
  "use strict";
        console.log("custom script included successfully");
If you want to include any third party min JS files you can place it here and you can call its API. 
Using this method, your custom javascript file will be called using require js.

You can see Magento 2 core modules uses both the methods. 

For First method, you can refer vendor\magento\module-paypal\view\adminhtml\layout\adminhtml_system_config_edit.xml

For Second method, you can refer vendor\magento\module-customer\view\adminhtml\layout\customer_index_edit.xml

No comments:

Post a Comment