Magento E-commerce Platform Q/ A

How to Add a Category Tree with Checkboxes (Admin Interface) into a Custom Magento Module

In Tabs.php file of custom module in  _beforeToHtml method we will add a custom tab after the main (default) tab and will place a category tree there:

$this->addTab('category_tree_tab', array(
		'label'     => Mage::helper('catalog')->__('Category Tree Tab'),
		'url'       => $this->getUrl('modulename/adminhtml_index/categories', array('_current' => true)),
		'class'     => 'ajax',
	));

 

Then in parameter url we should indicate the path to a method categoriesAction (method presented below)

Also we will add two methods to admin controller that save and load the page with our custom tab and its content. These methods will add a category tree to our custom tab:

public function categoriesAction()
 {
     $this->getResponse()->setBody(
         $this->getLayout()->createBlock('modulename/adminhtml_tree')->toHtml()
     );
 }
	
public function categoriesJsonAction() 
{
      $this->getResponse()->setBody( 
             $this->getLayout()->createBlock('modulename/adminhtml_tree')
		->getCategoryChildrenJson($this->getRequest()- >getParam('category'))
	    );
 }

 

Then we should create a new block based on Magento class: Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Categories.

class Namespace_Modulename_Block_Adminhtml_Tree extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Categories
	{
		// Checks when this block is readonly
		public function isReadonly()
		{
			return false;
		}

		protected function getCategoryIds()
		{
			$categories_ids_array = array();
			
			//PASTE YOUR CODE HERE TO GET THE ARRAY OF  CATEGORIES IDS THAT WERE ALREDY CHECKED TO LOAD CATEGORY TREE IN PREVIOUS CONDITOPN. 
			return $categories_ids_array;
		}

		public function getIdsString()
		{
			return implode(',', $this->getCategoryIds());
		}
	}

That's it, the category tree is done.

 

In order to save categories picked by user,  in method saveAction() of your controller modify 'category_ids' parameter:

	$selected_categories = $this->getRequest()->getParam('category_ids');