Showing posts with label custom script. Show all posts
Showing posts with label custom script. Show all posts

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="http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <referencecontainer name="js">
            <block class="Magento\Backend\Block\Template" name="admincustomjs" template="Your_Modulename::system/config/additional_script.phtml">
        </block></referencecontainer>
    </body>
</page>

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">
    require(
        ['jquery'],
        function($) {
            $(function() {
              console.log('custom script included successfully');
            });
          });
</script>

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="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
<link src="Your_Modulename::js/custom_require.js"/>
    </head>
    <body/>
</page>


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.

require([
    'Your_Modulename/custom_system_config'
]);
Create custom_system_config.js file inside view/adminhtml/web/
place your custom javascript in this file

define([
  "jquery"
],&nbsp
function($) {
  "use strict";
    $(document).ready(function($){
        console.log("custom script included successfully");
    });
    return;
});
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

Monday, 8 December 2014

Magento update backorder programatically

To update a products backorder status i wrote a custom script. My script reads the SKU's from the csv file and checks if the product exists and updates its backorder status.

Below is the code.

$products = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
if($products)
{     
   // get product's stock data such quantity, in_stock etc
   $stockData = Mage::getModel('cataloginventory/stock_item')->loadByProduct($products);
           
   //to update backorder
   $stockData->setData('use_config_backorders', '0'); //not to use config settings           
   /*0 = No Backorders
   1 = Allow Qty Below 0
   2 = Allow Qty Below 0 and Notify Customer*/
   $stockData->setData('backorders', '1');
                       
   // then set product's stock data to update
   $stockData->save();
           
   // call save() method to save your product with updated data
   $products->save();                
}


You can download the complete code here.  It reads the csv file and checks for the products, If it is found the data are updated. Upon running this file. It will output all the products status (Found, Not found, How many not found) in the webpage. It also Writes the missing sku's in a new CSV file.

Tuesday, 25 November 2014

Magento Customer Import - Convert plain text password to magento format.

One of my recent task is to import about 10k customers into Magento database.

First thing came into my mind is to export the existing customer from magento and use the csv file to fill in the new customer values and import them back.
But after exporting the few existing customers, i came to know that the CSV header fields which Magento exported is not suitable for the import and missing fields for password, customer address etc.

After few searches, i found this SAMPLE CSV file. click to download

Filled in the CSV file and for the password_hash field, I had to develop a customer script to convert plain text password to Magento format password.

My custom script is below. It reads the CSV file which contains plain text password, Encrypts it and writes to a new CSV file. After you CSV file is ready go to the admin panel. In the menu select System -> Import/Export -> Dataflow- Profiles. You will see "import customer". Click on it and upload your CSV file and click "save & continue edit" button. Then Choose the imported file from the dropdown and click Run.

All the customers will be imported with their previous password and addresses.

<?php
$row = 1;
$fp = fopen('var/log/ss1-pass.csv', 'w');
$csvHeader = array('Text','Encrypted');
fputcsv( $fp, $csvHeader,",");

//generate random string for salt
function generateRandomString($length = 2) {
    $characters = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

if (($handle = fopen("ss1.csv", "r")) !== FALSE) {

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      $row++;
      $plainText =  trim($data[0]);
      $salt = generateRandomString(2);
      $encrypted = md5($salt.$plainText).":".$salt;
      fputcsv($fp, array($plainText,$encrypted), ",");
      //if($row==20){break;}
    }
   
 fclose($handle);
 fclose($fp);
}
?>


Tuesday, 1 July 2014

Magento Add to cart not working for new products block

I came across this Add to cart issue after upgrading from version 1.7.2 to 1.8.1.
Then after a long time search, luckly i found the cause.

In Magento version 1.8.1 there was an update to the add to cart feature with the inclusion of "Form keys". Magento has implemented this feature to prevent XSS attacks.

To know more about Form keys click here.

SOLUTION : Change the button type from "button" to "submit"

NOTE : Enabling All cache type may not solve the issue. Disable only "Blocks HTML output", you can enable other cache types.