Form Drop Down population from recursive table

Hope somebody can help me! I’ve read a few similar topics but still can’t get it working the way I want it to.

I have a table that looks like this:




id

strName

intParentId



So there are rows that are children of other rows.

Obviously, on the form view I want a dropdown that displays the parents and children recursively.

for example I want the dropdown to look like this:

–Item 1

----Item 2

----Item 3

------Item 4

–Item 5

–Item 6

----Item 7

I have setup the relations as follows:

'getparent' => array(self::BELONGS_TO, 'Table', 'intParentID'),


'children' => array(self::HAS_MANY, 'Table', 'intParentID'),

I’ve tried creating a few recursive functions, but I just can’t seem to create one that makes an array that works in dropDownList.

Please help!!

You can try something like:




class Table {

	

	public function relations() {

		

		return array(

			'getparent' => array(self::BELONGS_TO, 'Table', 'intParentID'),

			'children' => array(self::HAS_MANY, 'Table', 'intParentID'),

		);

	}

	

	public function getDropdownItems($parentId = 0, $level = 0) {

		$itemsFormatted = array();

		

		$items = Table::model()->findAllByAttributes(array(

			'intParentID' => $parentId,

		));

		

		foreach ($items as $item) {

			$itemsFormatted[$item->id] = str_repeat('-', $level) . $item->strName;

			$itemsFormatted = array_merge($itemsFormatted, $this->getDropdownItems($item->id, $level + 1));

		}

		

		return $itemsFormatted;

	}

}


// usage

Chtml::dropDownList('mySelect', '<selected id>', Table::model()->getDropdownItems());



Amazing! Thanks for your reply. Have been at it all day and couldn’t suss it out.

Thanks again

Actually, scratch that - there’s a problem. The drop down it produces has the wrong values. I think it has something to do with array_merge, but I think it’s reindexing the keys so they just become sequential.

Any ideas?

Hm, yes, you’re right. array_merge somewhy reindex keys.

Try replace line:

$itemsFormatted = array_merge($itemsFormatted, $this->getDropdownItems($item->id, $level + 1));

To:

$itemsFormatted += $this->getDropdownItems($item->id, $level + 1);

Brilliant. Works perfectly. Thank you!