Hi, i’m new to Yii, so would like to share what i learned …
create a drop-down list to use in forms containing data from a table in the database.
The table contains property types as follows
id parent_id name
1 0 A
2 0 B
3 1 AB
4 3 ABC
5 2 BA
6 0 D
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
........
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'parent' => array(self::BELONGS_TO, 'departments', 'parent_id', 'condition' => 't.parent_id <> 0'),
'children' => array(self::HAS_MANY, 'departments', 'parent_id'),
);
}
........
In your view within form widgets
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form-id',
'enableAjaxValidation'=>false,
)); ?>
......
<div class="row">
<?php
$parents = Departments::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>
......
Hope this could help someone…
there’s always room for improvement, waiting for feedback
Thanks