Top Menu

Creating multi-level category system with PHP & Yii (MVC Framework) in not just a simple undertaking.
Many Developer usage different type to handle this specific. They may possibly create 3 tables for initial level, subsequent level as well as 3rd level category (parent, sub category as well as sub sub cateogry).
The best method to acquire multi-level category using recursive function.
With this, let us build a database table i.e category. as shown below

At first, we create our SQL-Table
CREATE TABLE `menus` ( `id` int(11) NOT NULL, `name`
varchar(150) CHARACTER SET utf8 NOT NULL, `link` varchar(500)
CHARACTER SET utf8 NOT NULL, `parent_id` int(11) NOT NULL, `class_style`
varchar(100) CHARACTER SET utf8 NOT NULL, `order_by` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0' COMMENT '0-->active,1-->Inactive', `menu_type` int(11) NOT NULL DEFAULT '0' COMMENT '0-->admin,1-->Telicaller', `created` date NOT NULL )
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  1. Create-ulti-level-category

Firstly Create database like attachment, with the help of phpmyadmin
For example I have a table like this
screenshot-127.0.0.1-2017-03-11-17-13-58
Create Function in models

function getRootCategory($cur_cat='') {
$sql='select id, course_name, parent_id from course where parent_id="0" and status=0'; $command=Yii::app()->db->createCommand($sql);
$return =$command->queryAll();
foreach($return as $rootCat){
if ($rootCat['id']==$cur_cat){
$test= 'selected=selected'; }else{
$test=''; }
$id=$rootCat['id'];
echo "".$rootCat['course_name'].'';
$this->sub_cat($rootCat['id'] , '', $cur_cat ); } }
function sub_cat($parentID=0, $space='',$cur_cat ) {
$sql="select id, course_name, parent_id from course where parent_id='$parentID' and status=0";
$command=Yii::app()->db->createCommand($sql);
$return =$command->queryAll();
$count=count($return);
if($parentID==0){ $space=''; }else{ $space .=" - "; }
if($count > 0){
foreach($return as $subcat){
if ($subcat['id']==$cur_cat){$test='selected=selected';}else{$test='';}
$ids=$subcat['id'];
echo "".$space.$subcat['course_name'].'';
$this->sub_cat($subcat['id'],$space, $cur_cat ); } } }
Now create this code in view/file.php
<?php
echo ‘<select id=”parent_id” class=”select” name=”Course[parent_id]” >’;
echo “<option value=’0′  >–Select Exam–</option>”;
echo Course::model()->getRootCategory($model->parent_id);
// ($model->parent_id) means selected text box
echo ‘</select>’; ?>

About The Author

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>