You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.
In this tutorial we will create a hierarchical Structure using the traditional adjacency list model. Yii's ActiveRecord paradigm makes it very easy to implement this structure via a join on itself. After this, we will use the new CMenu from yii 1.1 and implement it in conjunction with superfish, a jQuery plugin for creating menus.
I will also add a tutorial using a Nested Set (using the wonderful nested set extension) soon.
At first, we create our SQL-Table containing our hierarchical data like this:
[sql]
CREATE TABLE `Hierarchy` ( <br />
`id` int(11) NOT NULL auto_increment, <br />
`sort` int(11) NOT NULL, <br />
`parent` int(11) default NULL, <br />
`title` varchar(255) default NULL, <br />
PRIMARY KEY (`id`)
) ENGINE=InnoDB
You may add additional Columns if you wish, and you can rename the table however you like. The 'parent' field contains the id of the direct parent, while 'sort' defines, where our row gets displayed in the menu.
After that, we generate the model and a C-R-U-D interface:
$ php protected/yiic shell <br />
Yii Interactive Tool v1.1 (based on Yii v1.1.0) <br />
Please type 'help' for help. Type 'exit' to quit. <br />
>> model Hierarchy <br />
>> crud Hierarchy <br />
When this commands run without an error, we should add two relation rules to our new created model:
public function relations() <br />
{ <br />
return array( <br />
'getparent' => array(self::BELONGS_TO, 'Hierarchy', 'parent'), <br />
'childs' => array(self::HAS_MANY, 'Hierarchy', 'parent', 'order' => 'sort ASC'), <br />
); <br />
This reads as: the 'parent' of a row belongs to the parent-column of the same table, while we can gather the childs of a row by a relation of ourself with the HAS_MANY relation. We always want our childs get ordered by the column 'sort's. You can add additional relations if you want.
To test our newly created model, we need to insert some random test data:
[sql]
insert into Hierarchy (id, sort, parent, title) values(1, 0, 0, 'root'); <br />
insert into Hierarchy (id, sort, parent, title) values(2, 0, 1, 'First Entry'); <br />
insert into Hierarchy (id, sort, parent, title) values(3, 0, 1, 'Second Entry withoud Childs'); <br />
insert into Hierarchy (id, sort, parent, title) values(4, 0, 1, 'Third Entry'); <br />
insert into Hierarchy (id, sort, parent, title) values(5, 0, 3, 'Child of the third Entry'); <br />
insert into Hierarchy (id, sort, parent, title) values(6, 0, 5, 'Child of the Child of the third Entry'); <br />
insert into Hierarchy (id, sort, parent, title) values(7, 0, 1, 'Child of the first Entry'); <br />
Now, in our yii console or in the Application we can use
$model = Hierarchy::model()->findByPk(7); <br />
$parent = $model->parent; <br />
echo $parent->title; <br />
// returns 'First Entry' <br />
to get the parent element, or
$model = Hierarchy::model()->findByPk(1); <br />
print_r($model->childs); <br />
to print out all existing models in our Database. As you may suggest, this output is not very nice. Since we want to use the CHtml module of yii 1.1, we need to format our Output in an array like this:
public function getListed() { <br />
$subitems = array(); <br />
if($this->childs) foreach($this->childs as $child) { <br />
$subitems[] = $child->getListed(); <br />
} <br />
$returnarray = array('label' => $this->headline, 'url' => array('Hierarchy/view', 'id' => $this->id)); <br />
if($subitems != array()) $returnarray = array_merge($returnarray, array('items' => $subitems)); <br />
return $returnarray; <br />
} <br />
We place this function in models/Hierarchy.php
This is a recursive function (note how the function calls itself) that gathers all subchilds of an element that are available in the Database. Of course, when we run this function on our root node, we get all non-orphan childs.
After that, we can use the CMenu-Widget to generate our Menu:
$model = Hierarchy::model()->findByPk(1); <br />
$items[] = $model->getListed(); // note that the [] is important, otherwise CMenu will crash. <br />
<br />
$this->widget('zii.widgets.CMenu',array( <br />
'items'=>$items, <br />
'htmlOptions' => array('class' => 'sf-menu') // needed for superfish integration, see below... <br />
)); <br />
to render the menu with the content of our database. This already looks nice, but we want to have a real drop-drown menu. The CHtml-Menu does not contain this feature at this moment, so we use a nice jquery plugin called superfish. Thanks to jquery, this fit's really easy into our Application. After downloading and extracting superfish, just put this line in your layout file views/layouts/main.php :
[html]
<link rel="stylesheet" type="text/css" media="screen" href="superfish.css" /> <br />
<script type="text/javascript" src="hoverIntent.js"></script> // <-- optional <br />
<script type="text/javascript" src="superfish.js">
Then, we need our Script to replace the existing ul-structure with the superfish-plugin: ~~~ [html]
$(document).ready(function(){ <br />
$("ul.sf-menu").superfish(); <br />
}); <br />
~~~
Since we have defined the class of our ul-element to be 'sf-menu', this script snippet will replace our structure with the power of superfish. Note the bunch of effects and options (like drop-shadow) you can configure with superfish.
After this, we want our Users to be able to easily move Menu entries around. To achieve this, we will use a Drop-Down List, in which we can choose the parent of our selected element. We write this code-snippet to views/Hierarchy/_form.php :
$data = Hierarchy::model()->findAll('parent=:parent', array('parent' => '0')); <br />
foreach($data as $child) { <br />
$subchilds = $child->childs; <br />
foreach($subchilds as $subchild) { <br />
$subchild->title = $subchild->getparent->title . "|" . $subchild->title; <br />
$data = array_merge($data, $child->childs); <br />
} <br />
} <br />
<br />
$rootobj = new Hierarchy; <br />
$rootobj->id = 0; <br />
$rootobj->title = "root level"; <br />
$root = array($rootobj); <br />
$data = array_merge($root, $data); <br />
if(isset($model->id) && $model->id == 1) { <br />
echo "This is the root node and can't be moved."; <br />
$model->parent = 0; <br />
} <br />
else { <br />
if(isset($_GET['hierarchyParent'])) <br />
echo CHtml::DropDownList('Hierarchy[parent]', $_GET['HierarchyParent'], CHtml::listData($data, 'id', 'title')); <br />
else if($update) <br />
echo CHtml::DropDownList('Hierarchy[parent]', $model->parent, CHtml::listData($data, 'id', 'title')); <br />
else <br />
echo CHtml::DropDownList('Hierarchy[parent]', 1, CHtml::listData($data, 'id', 'title')); <br />
} <br />
Note the lines
if(isset($_GET['hierarchyParent'])) <br />
echo CHtml::DropDownList('Hierarchy[parent]', $_GET['HierarchyParent'], CHtml::listData($data, 'id', 'title')); <br />
With this lines we will be able to create a "add entry to this element"-Button like this:
if(!Yii::app()->User->isguest) <br />
echo CHtml::link("Add a new element", array('Hierarchy/create', 'hierarchyParent' => $model->id)); <br />
Place this lines somewhere at views/Hierarchy/view.php .
I hope my small tutorial was helpful for you. There are some points that can be made even better, for example someone could change the admin CGridView to be collapsable, and the elements could be moved around by drag & drop. In the next version of this Tutorial i will use the nestedset extension to achieve the Hierarchy Structure. Thank you for reading & trying, and don't hesitate to ask me when you have Questions.
Display all menu items
Using loop to display all items:
$Hierarchy=Hierarchy::model()->findAll(array('condition'=>'parent = 0')); foreach ($Hierarchy as $Hierarchy){ $models = Cat::model()->findBypk($Hierarchy->id); $items[] = $models->getListed(); } if($items[0]['items'] != "0"){ $items = array_merge(array('items'=>array('label'=>'Trang chủ', 'url'=>array('/site/index'))), $items,array(array('label'=>'Liên hệ', 'url'=>array('/site/contact')))); $this->widget('zii.widgets.CMenu',array( 'items'=>$items, ));
Error
I get this error, while running the code
Alias "zii.widgets.CDropDownMenu" is invalid. Make sure it points to an existing PHP file.
Any ideas why?
@abhimir
Have you installed the CDropDownMenu extension?
you have the link to this extension at the begining of the article...
@mdomba
I have installed the CDropDownMenu... and added it in the main config file as
'import'=>array( 'application.models.*', 'application.components.*', 'application.modules.user.models.*', 'application.modules.user.components.*', 'application.extensions.*' ),
Maybe I am not initialising it correctly?
@abhimir
Seems this is an error...
If you put CDropDownMenu in the protected/extensions folder, try with
$this->widget('application.extensions.CDropDownMenu',...
@mdomba
It works now, thanks. Had to make a few other changes, but the code works perfectly now.
Tree View
Hi,
your example works perfect but is it possible to make it work with the CtreeView ?
Thanks
Undefined variable: update
gives me an error
Illegal string offset 'label'
Hi I am trying this code by passing hardcoded variable .However it gives the error as "Illegal string offset 'label' ".
$title = 'Main' ;
$subitems = array();
$subitems[] = 'one';
$subitems[] = 'two';
$returnarray = array('label' => $title, 'url' => array('Hierarchy/view')); $returnarray = array_merge($returnarray, array('items' => $subitems)); $items[] = $returnarray; $this->widget('ext.CDropDownMenu.CDropDownMenu',array( 'items'=>$items,));
Any suggestions regarding the error please ?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.