In this tutorial, we create tree structure dropdown list like as below :-
RHCE
--SE1
RHCSA
--SA1
--SA2
PHP
Table strucure for this kind of tree is as below :
id parent_id course_name
1 0 RHCE
2 0 RHCSA
3 1 SE1
4 2 SA1
5 2 SA2
6 0 PHP
I have create class file in component folder because i can use it anywhere in my application but you can create this file's function anywhere.
In components folder create a new class CommonMethods.
<?php
/*
* /protected/components/CommonMethods.php
*/
class CommonMethods {
private $data = array();
public function makeDropDown($parents)
{
global $data;
$data = array();
$data['0'] = '-- ROOT --';
foreach($parents as $parent)
{
$data[$parent->id] = $parent->name;
$this->subDropDown($parent->children);
}
return $data;
}
public function subDropDown($children,$space = '---')
{
global $data;
foreach($children as $child)
{
$data[$child->id] = $space.$child->name;
$this->subDropDown($child->children,$space.'---');
}
}
}
?>
In you model make relations.
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'CourseMaster', 'parent_id', 'condition' => 't.parent_id <> 0'),
'children' => array(self::HAS_MANY, 'CourseMaster', 'parent_id'),
);
}
In your view _form.php
<div class="row">
<?php
$parents = CourseMaster::model()->findAll('parent_id = 0');
$cm = new CommonMethods();
$data = $cm->makeDropDown($parents);
echo $form->labelEx($model,'parent_id');
echo $form->dropDownList($model,'parent_id', $data);
?>
</div>
RHCE
--SE1
RHCSA
--SA1
--SA2
PHP
Table strucure for this kind of tree is as below :
id parent_id course_name
1 0 RHCE
2 0 RHCSA
3 1 SE1
4 2 SA1
5 2 SA2
6 0 PHP
I have create class file in component folder because i can use it anywhere in my application but you can create this file's function anywhere.
In components folder create a new class CommonMethods.
<?php
/*
* /protected/components/CommonMethods.php
*/
class CommonMethods {
private $data = array();
public function makeDropDown($parents)
{
global $data;
$data = array();
$data['0'] = '-- ROOT --';
foreach($parents as $parent)
{
$data[$parent->id] = $parent->name;
$this->subDropDown($parent->children);
}
return $data;
}
public function subDropDown($children,$space = '---')
{
global $data;
foreach($children as $child)
{
$data[$child->id] = $space.$child->name;
$this->subDropDown($child->children,$space.'---');
}
}
}
?>
In you model make relations.
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'CourseMaster', 'parent_id', 'condition' => 't.parent_id <> 0'),
'children' => array(self::HAS_MANY, 'CourseMaster', 'parent_id'),
);
}
In your view _form.php
<div class="row">
<?php
$parents = CourseMaster::model()->findAll('parent_id = 0');
$cm = new CommonMethods();
$data = $cm->makeDropDown($parents);
echo $form->labelEx($model,'parent_id');
echo $form->dropDownList($model,'parent_id', $data);
?>
</div>
No comments:
Post a Comment