Archive for February, 2013

Add Category Tree Structure in Magento

public function getCategories()
/*$category = Mage::getModel(‘catalog/category’);
$tree = $category->getTreeModel();
$ids = $tree->getCollection()->getAllIds();
$arr = array();
if ($ids)
foreach ($ids as $id)
$cat = Mage::getModel(‘catalog/category’);
//$arr[$id] = $cat->getName();
$arr[] = array(‘value’=> $id,’label’=> $cat->getName());
return $arr;    */
$categories = Mage::getModel(‘catalog/category’)

$all = array();
foreach ($categories as $c)
//$all[$c] = $c->getName();

if($level > 1){
for($i=1;$i< $level;$i++)
$prestr.=’- ‘;


$all[] = array(‘value’=> $c->getId(),’label’=> $prestr.$c->getName());

return $all;



public function getCategories()
$model  =   Mage::getModel(‘catalog/category’);
$rootCategoryId = Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId();
$category = $model->load($rootCategoryId);

$all= Mage::helper(‘brand’)->getCategoriesCustom($category,$rootCategoryId,$result);
return $all;


In Data.php File,

public function getCategoriesCustom($parent,$curId,$result){

if($parent->getLevel() == 1){
$result[]=array(‘value’=> $curId,’label’=> $this->getCatNameCustom($parent));
$result[]=array(‘value’=> $parent->getId(),’label’=> $this->getCatNameCustom($parent));

$children = $parent->getChildrenCategories();

if(count($children) > 0){
foreach($children as $cat){
catch(Exception $e){
return ”;
return $result;

public function getCatNameCustom($category){
$level = $category->getLevel();
$html = ”;
for($i = 0;$i < $level;$i++){
$html .= ‘-‘;
if($level == 1)    return $html.’ ‘.$this->__(“All Categories”);
else return $html.’ ‘.$category->getName();




Add Multiselect field in Magento Admin Form

Add following code into _prepareForm() function in Form.php file.

$fieldset->addField(‘news_id’, ‘multiselect’, array(
‘label’     => Mage::helper(‘designer’)->__(‘News’),
‘required’  => false,
‘style’      => ‘width:400px’,
‘name’      => ‘news_id’,
‘values’    => Mage::getSingleton(‘designer/news’)->getNewsAll(),

Create new file News.php in Model folder and add following code into this file.

class Namespace_Designer_Model_News extends Mage_Core_Model_Abstract{

public function getNewsAll(){
// $news1 = Mage::getModel(‘news/state’)->getCollection();
$result = array();
$news = Mage::getModel(‘news/state’)->getCollection();
foreach ($news as $news1)
$addressLabel = $news1->getTitle();
//if (($addressLabel = $news1->getTitle()))
$result[] = array(‘value’=>$news1->getId(),’label’=>$addressLabel);

return $result;


Add following code into saveAction() function in DesignerController.php file.

$news_id1 = $data[‘news_id’];
$news_id = implode(“,”, $news_id1);

Set this $news_id in $model collection.

For Example,

$model = Mage::getModel(‘designer/designer’);

Now, Convert these news ids into array by following code.

For Example,

$latest_news_id = $designers[‘news_id’];

if (isset($latest_news_id)) {
$latest_news_id = explode(‘,’,$latest_news_id);
if (is_array($latest_news_id)) {
$latest_news_id = array_unique($latest_news_id);
$news1 = Mage::getModel(‘news/state’)->getCollection()->addFieldToFilter(‘id’, array(‘in’ => $latest_news_id))->setOrder(‘id’,’desc’);

Image Resize in Magento

/* Image */
      $image_width = 216;
      $image_height = 109;
   $fileName = $post['image'];
    if(!file_exists("./media/blog/resized/".$image_width."x".$image_height))     mkdir("./media/blog/resized/".$image_width."x".$image_height,0777);
  $folderURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."blog/";
    $imageURL = $folderURL . $fileName;
    $basePath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS ."blog". DS . $fileName;
   $newPath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS ."blog". DS . "resized" . DS .$image_width."x".$image_height. DS . $fileName;
    //if width empty then return original size image's URL
        //if image has already resized then just return URL
        if (file_exists($basePath) && is_file($basePath) && !file_exists($newPath)) {
            $imageObj = new Varien_Image($basePath);
            $imageObj->resize($image_width, $image_height);
      $resizedURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . "blog/resized" . '/' .$image_width."x".$image_height."/". $fileName;

 <p><a href="<?php echo $post->getAddress(); ?>" ><img src="<?php echo $resizedURL; ?>" /></a></p>

Add Extra Menu Item and Links to System Configuration Section in Custom Module in Magento

Add following code in app/code/local/[Name_Space]/[Module_Name]/etc/config.xml for add extra  menu item.

            <news module="news">
                    <items module="news">
                        <title>Manage Items</title>
                    <items1 module="news">
                        <title>Import News Data</title>

Note that here news will be the same as section name in system.xml file.

Sorting Admin Grid Fields with AJAX in Magento

Add follwing code into __construct() function in app/code/local/[Name_Space]/[Module_Name]/Block/Adminhtml/[Module_Name]/Grid.php file.


Now Add following function at last of this file.

public function getGridUrl()
      return $this->getUrl('*/*/grid', array('_current'=>true));

Now Add following function at last in app/code/local/[Name_Space]/[Module_Name]/controllers/Adminhtml/[Module_Name]Controller.php file.

public function gridAction()

Display Admin Form Field only Readonly in Magento

Add follwing code into _prepareForm() function.

$fieldset->addField('professor_firstname', 'text', array(
          'label'     => Mage::helper('deskcopy')->__('Professor First Name'),
          'readonly' => true,
          'name'      => 'professor_firstname',


$fieldset->addField('professor_firstname', 'hidden', array(
            'label'     => Mage::helper('deskcopy')->__('Professor First Name'),
            'after_element_html' => '<tr><td><label for="title">Professor First Name</label></td>
                <td>' .$data['professor_firstname'] . '</td></tr>',


Upgrade file in custom module in Magento

If you want to add extra fields in database table then you have to create upgrade file as follows.

Give file name as higher version from previous version.

For example if you have “mysql4-install-0.1.0.php.” file then upgrade file would be “mysql4-upgrade-0.1.0-0.1.1.php”.

Add following code for add extra fields.


$installer = $this;



— DROP TABLE IF EXISTS {$this->getTable(‘news’)};
ALTER TABLE {$this->getTable(‘news’)} ADD (
`title1` varchar(255) NOT NULL default ”,
`title2` varchar(255) NOT NULL default ”



Please note that you have to change version from 0.1.0 to 0.1.1 into config.xml file.

Clear magento cache and show result.