Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create Category Tree Structure in cake php

    • 0
    • 1
    • 0
    • 1
    • 1
    • 0
    • 0
    • 0
    • 2.92k
    Comment on it

    Hello readers. This is a small blog on Tree structure. How to add , update and delete category in this structure. Now we will create a category tree using cakephp. Category tree is like parent - child type records. Well will add new category, update and delete the existing category.
     
    Step 1:  Make a table structure categories in your database.
              

    CREATE TABLE categories (
    id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    parent_id INTEGER(10) DEFAULT NULL,
    lft INTEGER(10) DEFAULT NULL,
    rght INTEGER(10) DEFAULT NULL,
    name VARCHAR(255) DEFAULT '',
    PRIMARY KEY  (id)
    );


     
     
    Now insert some records in your table.
     

    INSERT INTO `categories` (`id`, `name`, `parent_id`, `lft`, `rght`) VALUES(1, 'Tutorials', NULL, 1, 8);
    INSERT INTO `categories` (`id`, `name`, `parent_id`, `lft`, `rght`) VALUES(2, 'PHP', 1, 2, 5);
    INSERT INTO `categories` (`id`, `name`, `parent_id`, `lft`, `rght`) VALUES(3, 'MySQL', 1, 6, 7);
    INSERT INTO `categories` (`id`, `name`, `parent_id`, `lft`, `rght`) VALUES(4, 'CakePHP', 2, 3, 4);


     
     
    Step 2: Now we will create file Category.php in app/Model. Add below written code in this file. The variable $actAs tells cakephp to attach 'Tree' behavior to this model, now  Cake will generate a Tree data structure for category model.
     

    <?php
     
       class Category extends AppModel {   
     
             var $name = 'Category';
     
              var $actsAs = array('Tree');
     
    }
     
    ?>


     
     
    Step 3: Next we will create a file CategoriesController.php in app/Controller. Add following code in this file.
     
    generateTreeList() method generates a tree-type structure for our Categories. Compact()  function is used to pass variables to your tree structure in CakePHP. Compact() method detects the variables having the same name  in your Controller and splits them as an array(). Now $this->set() is used to set those values for using them in your view file.
     
     

    <?php
               class CategoriesController extends AppController {
                   var $name = 'Categories';   
                  
                   function index() {
                      $categories = $this->Category->generateTreeList(null, null, null, '&nbsp;&nbsp;&nbsp;');
                      $this->set(compact('categories'));     
                      }
           }
    ?>


     
     
    Step 4: Next we will create our index.php in /app/views/categories/index.ctp. Add the following code in index file.
     
     

    <?php
          echo $this->Html->link("Add Category",array('action'=>'add'));
          echo "<ul>";
          foreach($categories as $key=>$value){
         $edit = $this->Html->link("Edit", array('action'=>'edit', $key));
         $delete = $this->Html->link("Delete", array('action'=>'delete', $key));
         echo "<li>$value &nbsp;[$edit]&nbsp;[$delete]</li>";
        }
        echo "</ul>";
    ?>


     
    Now open your browser and type  http://localhost/cakephp/categories, and you should see :
     
    > Tutorials     
     
       > PHP     
         > CakePHP     
       > MySQL
     
     
    Step 5: Now we will add new category in the list. Paste below code in your file CategoriesController.php
     
     

    function add() {
    if (!empty($this -> data) ) {
    $this->Category->save($this -> data);
    $this->Session->setFlash('A new category has been added');
    $this->redirect(array('action' => 'index'));
    } else {
    $parents[0] = "[Top]";
    $categories = $this->Category->generateTreeList(null,null,null," - ");
    if($categories) {
    foreach ($categories as $key=>$value)
    $parents[$key] = $value;
    }
    $this->set(compact('parents'));
    }
    }


     
     
    Step 6: Now we need to create a view file for add(). Make a file add.ctp in app/View/Categories/add.ctp. Paste this code in add.ctp Now see  on browser http://localhost/cakephp-tree/categories/add
     
     

    <h1>Add a new category</h1>
    <?php
    echo $form->create('Category');
    echo $form->input('parent_id',array('label'=>'Parent'));
    echo $form->input('name',array('label'=>'Name'));
    echo $form->end('Add');
    ?>


     
    Step7:  Open file CategoriesController.php and paste this code in this file.
     
     

    function edit($id=null) {
    if (!empty($this->data)) {
    if($this->Category->save($this->data)==false)
    $this->Session->setFlash('Error saving Node.');
    $this->redirect(array('action'=>'index'));
    } else {
    if($id==null) die("No ID received");
    $this->data = $this->Category->read(null, $id);
    $parents[0] = "[ Top ]";
    $categories = $this->Category->generateTreeList(null,null,null," - ");
    if($categories)
    foreach ($categories as $key=>$value)
    $parents[$key] = $value;
    $this->set(compact('parents'));
    }
    }


     
     
    Step 8: Next we will make a view file for edit(). Make a file in edit.ctp in view folder and paste the below written code in edit.ctp.
     
     

    <?php
     echo $this->Html->link('Back',array('action'=>'index'));
     echo $this->Form->create('Category');
      echo $this->Form->hidden('id');
      echo $this->Form->input('name');
      echo $this->Form->input('parent_id', array('selected'=>$this->data['Category']['parent_id']));
      echo $this->Form->end('Update');
    ?>


     
     
    Step 9: Now for delete category. Paste delete function in your controller.
     
     
     

    function delete($id=null) {
      if($id==null)
      die("No ID received");
      $this->Category->id=$id;
      if($this->Category->removeFromTree($id,true)==false)
         $this->Session->setFlash('The Category could not be deleted.');
       $this->Session->setFlash('Category has been deleted.');
       $this->redirect(array('action'=>'index'));
    }

    Done

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: