Hey guys,
I found a recursive function (by CraZyLeGs) to re-write the results
array to allow for multiple levels on the cake trac system (https://
trac.cakephp.org/ticket/486).
I have modified the original code slightly, to insert into my
AppModel.
function getTree($conditions=null, $fields=null, $sort=null)
{
$data = $this->findAll($conditions, $fields, $sort);
$rows = array();
foreach($data as $row)
{
$rows[$row[$this->name]['id']] = $row;
if ($row[$this->name]['parent_id'] == 0)
$roots[] = $row[$this->name]['id'];
}
while (count(array_diff(array_keys($rows), $roots)) > 0)
{
$theLeaves = $this->_getLeaves($rows);
foreach ($theLeaves as $leafId)
{
$rows[$rows[$leafId][$this->name]['parent_id']]['children']
[$leafId] = $rows[$leafId];
unset($rows[$leafId]);
}
}
return $rows;
}
function _getLeaves($array)
{
$parents = array();
$candidates = array();
$leaves = array();
foreach ($array as $row) {
$parents[] = $row[$this->name]['parent_id'];
if ($row[$this->name]['parent_id'] != 0)
$candidates[] = $row[$this->name]['id'];
}
$leaves = array_diff($candidates, $parents);
return $leaves;
}
Instead of calling:
$this->data = $this->Page->findAllThreaded($conditions, $fields,
$sort);
...call:
$this->data = $this->Page->getTree($conditions, $fields, $sort);
I hope this helps others having similiar issues.
Cheers;
Poncho
On Apr 19, 9:46 pm, Poncho <[EMAIL PROTECTED]> wrote:
> Hey guys,
>
> This may be a stupid question, but I've looked around the internet and
> Googled with no results.
>
> I want to show a complete hierarchy of the Pages model. I want it to
> be displayed using <div>s with 'root', 'parent', 'child' &
> 'grandchild' css classes set. I have tried using Cake's built-in
> findByAllThreaded but I have only managed to get down to the 'child'
> level when I want to go down as far as the 'grandchild' level.
>
> Any pointers would be appreciated.
>
> So far the code I have for it is:
> function admin_index()
> {
> $this->Page->unbindAll();
> $this->data = $this->Page->findAllThreaded(null, array('Page.id',
> 'Page.parent_id', 'Page.title', 'Page.slug','Page.created'),
> 'Page.created ASC');
> $this->set('data',$this->data);
>
> }
>
> The table structure looks like this:
> Field Type Null Key
> Default Extra
> id int(11) unsigned PRI
> NULL auto_increment
> parent_id int(11) unsigned YES NULL
> title varchar(255) YES
> NULL
> slug varchar(255) YES NULL
> content text
> created datetime
> 0000-00-00 00:00:00
> modified datetime
> 0000-00-00 00:00:00
>
> Cheers;
> Poncho
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Cake
PHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---