Custom category tree structure in Cakephp

Custom category  tree structure in Cakephp

Hi Friends,

Today i am going to explain Category Parent Child deep hierarchy in cakephp system, I think this is very useful functionality can be use in e-commerce, classfied  and news based websites  because these type of website have many more categories with deep hierarchy .

I am writing this post because i have created many websites and every time i needed to create such type of functionality for each system so i thought that i should write a post that will help for many developers that are facing such type of functionality.

So lets start with some steps :

We need some pages of Cakephp like

  1. Controller
  2. Model
  3. view
  4. webroots
  5. Categories mysql table with defined structure

First of all i am assuming that we have a database  that have a table named “categories“, and this mysql table have three columns.
id         name        parent_id
Or if you have not categories table then just use this code

  `name` varchar(100) NOT NULL,
   `parent_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)

INSERT INTO `categories` (`id`, `name`, `parent_id`) VALUES
(1, 'Fruits', ''),
(2,'Electronics', ''),
(3,'Furniture', ''),
(4,'Garden', ''),
(5,'Apples', 1),
(6,'Bananas', 1),
(7,'Green Apple', 5),
(8,'Red Apples', 5),
(9,'Mobiles', 2),
(10,'Televisions', 2),
(11,'Android', 9),
(12,'iPhone', 9),
(13,'Green Apples', 7),
(14,'Two Dozens Apples', 7);

You can import categories table and its structure and its data as well.
Steps: 2)
Now go to Model folder that can be found in app folder like this app/Model and create a php file called Category.php

Steps: 3) Go to Controller folder and this folder is located in app/Controller path so now you have to create a controller file called pageController(its defalt file) or you can create any controller file here but now i am using pageController.php so you can use my code

class PagesController extends AppController {

 * This controller does not use a model
 * @var array
	public $uses = array();

 * Displays a view
 * @return void
 * @throws NotFoundException When the view file could not be found
 *	or MissingViewException in debug mode.
	public function display() {
		$path = func_get_args();

		$count = count($path);
		if (!$count) {
			return $this->redirect('/');
		$page = $subpage = $title_for_layout = null;

		if (!empty($path[0])) {
			$page = $path[0];
		if (!empty($path[1])) {
			$subpage = $path[1];
		if (!empty($path[$count - 1])) {
			$title_for_layout = Inflector::humanize($path[$count - 1]);
		$result = $this->Category->find('all',array(
		'fields' => array(
			'name AS text',
			'parent_id' )) );
		$result = Set::extract('/Category/.', $result);
		$treeArray = $this->buildTree($result);

		$this->set(compact('page', 'subpage', 'title_for_layout','treeArray'));

		try {
			$this->render(implode('/', $path));
		} catch (MissingViewException $e) {
			if (Configure::read('debug')) {
				throw $e;
			throw new NotFoundException();

public function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = $this->buildTree($elements, $element['id']);
            if ($children) {
                $element['nodes'] = $children;
            $branch[] = $element;

    return $branch;

Steps: 4)
Lets go to View folder ,i am managing its view using a element called header.ctp that is located in app/View/Elements/
Now we are going to render its view so i used a jquery tree plugin that takes json array.

Now we need to add some jquery treeview plugin css and js file in cakephp layout file that located in app/View/Layouts and i am using default.ctp file for now so just open this files it is already exist for each cakephp setup.

	Html->charset(); ?>
		<?php echo $this->fetch('title'); ?>
		echo $this->fetch('meta');

	    echo $this->Html->script('bootstrap-treeview.min');

Session->flash(); ?>
element('header'); ?> fetch('content'); ?>
element('sql_dump'); ?>

Okay so last srep is to place jquery plugin js and css file in webroot folder that is lacated in app/webroot
now you have to place js file in js folder and css file in css folder .
Thats it
I am going to add both js and css file here.

So just download these files and placed into webroot files now our Category Tree structured is ready.

Leave a Reply

Your email address will not be published. Required fields are marked *