I am currently working on outputting a heirarchy in terms of a navigation menu from a nestedSet in Doctrine.
I have a number of parents that then have several children.
At the moment in time, there are only 2开发者_如何学JAVA levels: Parent and Child (no grandchildren).
I have the following code:
//actions:
public function executeShow(sfWebRequest $request)
{
$this->tree = Doctrine::getTable('Model')->getMenuTree();
}
//lib:
class ModelTable extends Doctrine_Table
{
/**
* Gets tree element in one query
*/
public function getMenuTree()
{
$q = $this->createQuery('g')
->orderBy('g.root_id')
->addOrderBy('g.lft')
->where('g.root_id NOT NULL');
return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY);
}
}
//template:
<?php function echoNode($tree, $parent=null) { ?>
<ul>
<?php foreach ($tree as $node): ?>
<li data-id='<?php echo $node['id'] ?>'>
<?php echo $node['name'] ?>
<?php if (count($node['__children']) > 0): ?>
<?php echo echoNode($node['__children'], $node) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php } ?>
<?php echo echoNode($tree) ?>
This renders out:
Parent Node 1
Child Node 1
Child Node 2
Parent Node 2
Child Node 3
Which is great.
The problem is, that I'd like my URLs to match the parent/child relationship.
Thus the URL for Child Node 2, would be /parent-node-1/child-node-2
(these as slug
fields).
So any child of a parent, needs to have the parent node's route slug as well.
I hope that make sense?
Thanks
Well, one way to hadle this is to use Doctrine_Core::HYDRATE_RECORD_HIERARCHY
hydration, which allows you to call methods on your nodes.
Now you can create a custom method for a node:
class Model extends BaseModel
{
public function __toString()
{
return $this->getSlug();
}
public function getUrl()
{
//getPath uses __toString method to render a node
$url = $this->getNode()->getPath('/', true);
return $url;
}
}
And call it in template like this:
<a href="<?php echo $node->getUrl() ?>"><?php echo $node['name'] ?></a>
精彩评论