Web\Menu: provide and render unique id

fixes #7083
This commit is contained in:
Thomas Gelf 2014-09-05 17:24:55 +02:00
parent e0dc972281
commit 4bb065d9bb
2 changed files with 46 additions and 4 deletions

View File

@ -61,15 +61,25 @@ class Menu implements RecursiveIterator
*/
protected $subMenus = array();
/**
* Parent menu
*
* @var Menu
*/
protected $parent;
/**
* Create a new menu
*
* @param int $id The id of this menu
* @param Zend_Config $config The configuration for this menu
*/
public function __construct($id, Zend_Config $config = null)
public function __construct($id, Zend_Config $config = null, Menu $parent = null)
{
$this->id = $id;
if ($parent !== null) {
$this->parent = $parent;
}
$this->setProperties($config);
}
@ -234,6 +244,30 @@ class Menu implements RecursiveIterator
return $this->id;
}
/**
* Get our ID without invalid characters
*
* @return string the ID
*/
protected function getSafeHtmlId()
{
return preg_replace('/[^a-zA-Z0-9]/', '_', $this->getId());
}
/**
* Get a unique menu item id
*
* @return string the ID
*/
public function getUniqueId()
{
if ($this->parent === null) {
return 'menuitem-' . $this->getSafeHtmlId();
} else {
return $this->parent->getUniqueId() . '-' . $this->getSafeHtmlId();
}
}
/**
* Set the title of this menu
*
@ -351,7 +385,7 @@ class Menu implements RecursiveIterator
public function addSubMenu($id, Zend_Config $menuConfig = null)
{
if (false === ($pos = strpos($id, '.'))) {
$subMenu = new self($id, $menuConfig);
$subMenu = new self($id, $menuConfig, $this);
$this->subMenus[$id] = $subMenu;
} else {
list($parentId, $id) = explode('.', $id, 2);
@ -618,4 +652,12 @@ class Menu implements RecursiveIterator
{
next($this->subMenus);
}
/**
* PHP 5.3 GC should not leak, but just to be on the safe side...
*/
public function __destruct()
{
$this->parent = null;
}
}

View File

@ -115,9 +115,9 @@ class MenuRenderer extends RecursiveIteratorIterator
if ($childIsActive || ($passedActiveChild && $this->getDepth() === 0)) {
$passedActiveChild &= $this->getDepth() !== 0;
$openTag = '<li class="active">';
$openTag = '<li class="active" id="' . $child->getUniqueId() . '">';
} else {
$openTag = '<li>';
$openTag = '<li id="' . $child->getUniqueId() . '">';
}
$content = $this->renderChild($child);
$closingTag = '</li>';