Monday, March 11, 2013

How to Override Magento Core Javascript Functionality

magento override javascript
In case you've ever had to modify core Magento functionality in the realm of the javascripts, this may come in handy.  Today, I needed to look into modifying some validation methods that are located in

js/prototype/validation.js

So what you'll want to do, at a high level, is:
  1. Figure out how many different places in Mage you'll need to insert your custom javascript 
  2. Insert your javascript via layout xml of some sort
  3. Extend the core javascript objects with your customizations
  4. Profit
Where do I need to insert my javascriptation?
In my case, I was looking for instances of js/prototype/validation.js in the core, and I actually found more than I was hoping to:
  • design/adminhtml/default/default/layout/dataflow.xml
  • design/adminhtml/default/default/layout/main.xml
  • design/adminhtml/default/default/template/forgotpassword.phtml
  • design/adminhtml/default/default/template/login.phtml
  • design/adminhtml/default/default/template/resetforgottenpassword.phtml
  • design/frontend/base/default/layout/page.xml
  • design/frontend/enterprise/iphone/layout/page.xml
  • design/install/default/default/template/page.phtml
So, in my case, really the only places that I needed to deal with were the main.xml and page.xml.  The others were cases where the additional validation wasn't really going to be necessary.

How do insert this bidniss?
Well, you would go ahead and insert via an addJs in the <default> route (most likely) just like any other custom javascript file.  You probably want to put it in a location like js/<yourtheme>/prototype/validation.js - in other words map the directory and filename to the one that you're overriding, just like you'd probably do when building a class rewrite in a local code pool PHP module.

And now, the magic.
Thanks to people much smarter than me, I was able to stumble onto this stackoverflow thread where there was some sweet insight into one of the nice features of Prototype.  Basically, you can extend any object via the addMethods() method.

Now in the case of adding a validation method, it's actually more straight forward, because all you need to do is call Validation..addAllThese().

Validation.addAllThese([
    ['validate-po', 'We don't ship to PO boxes, suckafoo.', function(v) {
        var no_po = v.toLowerCase();
        if((no_po.indexOf('po box')) >= 0) {
            return false;
        }else {
            return true;
        }
    }]
]);

Profit
Well there  you have it.  Now you have one less excuse to hack the core.


1 comment: