I want to build a tree-view menu from the data table categories
:
+------+-----------+--------+
| id | name | parent |
+------+-----------+--------+
| 1 | father1 | 0 |
| 2 | father2 | 0 |
| 3 | son1-1 | 1 |
| 4 | son1-2 | 1 |
| 5 | son2-1 | 2 |
| 6 | son1-1-1 | 3 |
| 7 | father3 | 0 |
+------+-----------+--------+
So I create a form class:
class CategoryForm extends Form
{
public function initialize($entity = null)
{
//...
$parent = new Select('parent',
$this->buildtreeview(Metas::find("type = 'category'")),
//Metas::find("type = 'category'"),
array(
'class' => 'form-control',
'using' => array('id', 'name'),
'useEmpty' => true,
'emptyText' => 'Toppest',
'emptyValue' => 0
));
$this->add($parent);
}
protected function buildtreeview($cate, $parent = 0, $level = 0)
{
$arr = array();
foreach ($cate as $c) {
if ($c->parent == $parent) {
$tmp = array();
$tmp['id'] = $c->id;
$tmp['name'] = $c->name;
$tmp['parent'] = $c->parent;
$tmp['level'] = $level + 1;
$arr[] = $tmp;
$arr = array_merge($arr, self::buildtreeview($cate, $tmp['id'], $tmp['level']));
}
}
return $arr;
}
}
but it actually produce HTML like this:
<select id="parent" name="parent" class="form-control">
<optgroup label="0">
<option value="id">1</option>
<option value="name">father1</option>
<option value="parent">0</option>
<option value="level">1</option>
</optgroup>
<optgroup label="1">
<option value="id">3</option>
<option value="name">son1-1</option>
<option value="parent">1</option>
<option value="level">2</option>
</optgroup>
</select>
Firstly, the data is not complete, it has only two array item! (it actually has 7 items)
Secondly, I want to use only the [``id``, ``name``]
pair, but it seems doesn't work! I want it produces the HTML like this:
<select id="parent" name="parent" class="form-control">
<option value="0" selected>...</option>
<option value="1">father1</option>
<option value="3">---son1-1</option>
<option value="6">-------son1-1-1</option>
<option value="4">---son1-2</option>
<option value="2">father2</option>
<option value="5">---son2-1</option>
<option value="7">father3</option>
</select>
What's wrong?