Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JS programmatically in Magento?

I need to add a JS file conditionally and programmatically inside a block file. I tried with these codes:

if (Mage::getStoreConfig('mymodule/settings/enable')) {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file1.js');
} else {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file2.js');
}

However, regardless of what the setting is, none of this file is loaded. I even tried to eliminate the condition and explicitly load one file only, but it still doesn't work. What have I done wrong here?

like image 525
user1576748 Avatar asked Aug 13 '12 15:08

user1576748


2 Answers

The issue here is likely one of processing order. My guess is that your PHP code is being evaluated after the head block has been rendered. While your code is successfully updating the head block class instance, it's happening after output has been generated from that instance.

The better solution will be to add the addJs() calls in layout XML so that they will be processed prior to rendering. It would be nice if there were an ifnotconfig attribute, but for now you can use a helper.

Create a helper class with a method which returns the script path based on the config settings, then use this as the return argument.

<?php 
class My_Module_Helper_Class extends Mage_Core_Helper_Abstract
{
    public function getJsBasedOnConfig()
    {
        if (Mage::getStoreConfigFlag('mymodule/settings/enable')) {
            return 'path-to-file/file1.js';
        }
        else {
            return 'path-to-file/file2.js';
        }
    }
}

Then in layout XML:

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="head">
            <action method="addJs">
                <file helper="classgroup/class/getJsBasedOnConfig" />
                <!-- i.e. Mage::helper('module/helper')->getJsBasedOnConfig() -->
            </action>
        </reference>
    </default>
</layout>
like image 95
benmarks Avatar answered Oct 20 '22 00:10

benmarks


$this->getLayout()->getBlock('head')->addJs('path');

Its the right code, search if your path is right.

like image 37
Guerra Avatar answered Oct 19 '22 22:10

Guerra