Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Zf2 Como Crear View Helper Navigation

Estas en el tema de Zf2 Como Crear View Helper Navigation en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Buenas, Tal como dice el título, como se configura un module para que un View Helper modifique la estructura de un menú Navigation? Esto lo ...
  #1 (permalink)  
Antiguo 24/09/2012, 03:33
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Zf2 Como Crear View Helper Navigation

Buenas,

Tal como dice el título, como se configura un module para que un View Helper modifique la estructura de un menú Navigation?

Esto lo tengo en Zf1, con varios helpers que personalizan los distintos menús si son para el header, o footer.

Ayer busqué durante gran parte de la tarde, y nada de lo que encontré me dio resultado, además que las configuraciones de cada ejemplo eran totalmente distintas, así que no pude verificar cual era la que más se acercaba a la buena .

Se agradece un poco de orientación.

Gracias.
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #2 (permalink)  
Antiguo 24/09/2012, 05:58
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Que tal Uncontroled_Duck, no sigo muy bien la pregunta, no te funciona o estas preguntando donde es el mejor lugar para hacerlo ?, si es el segundo caso deberías utilizar un listener.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 24/09/2012, 06:47
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Hola masterpuppet,

El tema es que no se como configurarlo.

La idea es la siguiente:

Cuando creas un menú, te da entre otras, las opciones de configurar por cada enlace:
label, title, resource, privilege, class, etc.

En el caso del atributo class, este se aplica a la etiqueta <a>
Código HTML:
Ver original
  1. <li>
  2.     <a href="/" class="class">
  3. </li>

Mediante un ViewHelper, cambiaba esto, para que la clase se aplicara a la etiqueta <li>
Código HTML:
Ver original
  1. <li class="class">
  2.     <a href="/" class="class">
  3. </li>

El helper que tenía en Zf1 era así:
Código PHP:
class Zend_View_Helper_NavigationMenuLeftIcons extends
    
Zend_View_Helper_Navigation_Menu
{
    public function 
htmlify(Zend_Navigation_Page $page)
    {
        
//...
        
return '<' $element $this->_htmlAttribs($attribs) . '>'
        
$this->view->escape($label)
        . 
'</' $element '>';
    }
    
    protected function 
_renderMenu(Zend_Navigation_Container $container$ulClass$indent$minDepth$maxDepth$onlyActive)
    {
        
//...
        
return $html;
    }

Lo que intento es que unos helpers similares funcionen con los distintos menus en Zf2.

He intentado hacerlo de forma similar a algunos módulos de Git, pero como están orientados a hacer otras funciones, no se si están bien los cambios que hago.

Gracias por pasar. Un saludo,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #4 (permalink)  
Antiguo 24/09/2012, 07:32
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Lo que ha cambiado es la forma de generar el navigation, el renderizado es el mismo, hiciste el port de los view helpers y no te funcionan ?, postea el código que estas utilizando(en zf2)
__________________
http://es.phptherightway.com/
thats us riders :)
  #5 (permalink)  
Antiguo 24/09/2012, 11:43
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Hola masterpuppet,

El module donde estoy probando está así.
No tiene nada mas.

Código:
/module-dev
    /Reference
        /Navigation
            /config
                module.comfig.php
            /src
                Navigation
                    /Controller
                        IndexController.php
                    /View
                        /Helper
                            NavigationMenu.php
            /view
                /navigation
                    /index
                        index.phtml
            Module.php
            autoload_classmap.php
            autoload_function.php
            autoload_register.php
module.config.php
Código PHP:
return array(
    
'navigation' => array(
        
// The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
        
'default' => array(
            
// And finally, here is where we define our page hierarchy
            
array(
                
'label'      => 'Products',
                
'module'     => 'products',
                
'controller' => 'index',
                
'action'     => 'index',
                
'pages'      => array(
                    array(
                        
'label'      => 'Server',
                        
'module'     => 'navigation',
                        
'controller' => 'index',
                        
'action'     => 'index',
                        
'pages'      => array(
                            array(
                                
'label'      => 'Index',
                                
'module'     => 'index',
                                
'controller' => 'index',
                                
'action'     => 'index'
                            
),
                            array(
                                
'label'      => 'Editions',
                                
'module'     => 'products',
                                
'controller' => 'server',
                                
'action'     => 'editions'
                            
),
                            array(
                                
'label'      => 'System Requirements',
                                
'module'     => 'navigation',
                                
'controller' => 'index',
                                
'action'     => 'index'
                            
)
                        )
                    ),
                )
            ),
        ),
    ),
    
'controllers' => array(
        
'invokables' => array(
            
'Navigation\Controller\IndexController' => 'Navigation\Controller\IndexController',
        ),
    ),
    
'router' => array(
        
'routes' => array(
            
'navigation' => array(
                
'type'    => 'literal',
                
'options' => array(
                    
'route'       => '/navigation',
                    
'defaults' => array(
                            
'controller' => 'Navigation\Controller\IndexController',
                            
'action' => 'index',
                    ),
                ),
            ),
        ),
    ),
    
'view_helpers' => array(
        
'invokables' => array(
            
'navigationMenu' => 'Navigation\View\Helper\NavigationMenu',
        ),
    ),
    
'service_manager' => array(
       
'factories' => array(
           
'Navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory'
       
),
    ),
    
'view_manager' => array(
        
'template_path_stack' => array(
            
__DIR__ '/../view'
        
),
    ),
); 
NavigationMenu.php
Código PHP:
namespace NavigationViewHelper;

use 
ZendViewHelperAbstractHelper;
use 
ZendNavigationPageAbstractPage;

class 
NavigationMenu extends AbstractHelper
{
    public function 
htmlify(AbstractPage $page$escapeLabel true)
    {
        
var_dump($page); //solo para comprobar salida
    
}
    
    public function 
renderMenu($container null, array $options = array())
    {
        
var_dump($container); //solo para comprobar salida
    
}

index.phtml
Código PHP:
<?php
$label 
$this->navigation('Navigation')->findOneByLabel('Server');
$options = array(
    
'ulClass' => 'nav nav-list',
);
?>
<?php 
echo $this->navigation('Navigation')
                ->
findHelper('navigationMenu')
                ->
menu()
                ->
renderMenu($label$options); ?>
Module.php
Código PHP:
namespace ReferenceNavigation;

class 
Module
{
    public function 
getAutoloaderConfig()
    {
        return array(
            
'Zend\Loader\ClassMapAutoloader' => array(
                
__DIR__ '/autoload_classmap.php',
            ),
            
'Zend\Loader\StandardAutoloader' => array(
                
'namespaces' => array(
                    
__NAMESPACE__ => __DIR__ '/src/' __NAMESPACE__,
                ),
            ),
        );
    }

    public function 
getConfig()
    {
        return include 
__DIR__ '/config/module.config.php';
    }

    public function 
getViewHelperConfig()
    {
        return array(
            
'invokables' => array(
                
'navigationMenu' => 'Navigation\View\Helper\NavigationMenu',
            ),
        );
    }

Seguro que está todo

Gracias. Un saludo,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #6 (permalink)  
Antiguo 24/09/2012, 15:20
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

@Uncontroled_Duck talves estoy dormido pero sigo sin saber cual es el problema exactamente, te tira algún error o simplemente no hace nada ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #7 (permalink)  
Antiguo 25/09/2012, 04:05
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Cita:
Iniciado por masterpuppet Ver Mensaje
@Uncontroled_Duck talves estoy dormido pero sigo sin saber cual es el problema exactamente, te tira algún error o simplemente no hace nada ?
Ese es el tema, que no lanza ningún error y tampoco hace nada. Así qué no puedo ver si voy bien o si hay errores.

La forma de cargarlo entonces es correcta?

Saludos,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #8 (permalink)  
Antiguo 25/09/2012, 06:09
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Es raro que no te muestre ningún error, el tema es que el view helper tiene que estar registrado como invokable en el PluginManager de navigation, ademas tiene que implementar Zend\View\Helper\Navigation\AbstractHelper, en tu caso deberias extender directamente de Zend\View\Helper\Navigation\Menu, te dejo una posible solucíon, http://zend-framework-community.6341...td4656868.html, el OP pisa el factory que trae por defecto y le agrega el invokable, creo que lo hace de esta forma porque seguramente no encontró como obtener el Manager a través del locator.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #9 (permalink)  
Antiguo 26/09/2012, 12:11
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Hola masterpuppet,

No hay manera, y no me puedo creer, que algo tan sencillo en la versión anterior, sean tan complicado en esta.

Lo he probado con el ejemplo del enlace. Failed to find plugin for navigationMenu

Lo he probado copiando como lo hacen con el module ZfcUser. Failed to find plugin for navigationMenu

Encontre otro ejemplo distinto, lo probé y Failed to find plugin for navigationMenu

Todos con configuraciones distintas y ninguno encuentra el Helper.

Seguiré probando a ver si doy con la solución. Algo se me escapa y no termino de verlo.

Gracias por pasar,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #10 (permalink)  
Antiguo 26/09/2012, 12:28
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Suele suceder, a ver, hice una pequeño test y me funciona correctamente, asi lo tengo yo:

module.config.php
Código PHP:
Ver original
  1. ...
  2.  'service_manager' => array(
  3.      'factories' => array(      
  4.          'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory'
  5.     ),
  6.  ),
  7. ...
no es necesario que lo agregues a la key view_helpers.

Module.php
Código PHP:
Ver original
  1. ...
  2. public function getViewHelperConfig()
  3. {
  4.     return array(
  5.         'factories' => array(
  6.             'navigation' => function($pm) {
  7.                 $helper = new \Zend\View\Helper\Navigation;
  8.  
  9.                 $pm->injectRenderer($helper);
  10.  
  11.                 $helper->setServiceLocator($pm->getServiceLocator());
  12.                 $helper->getPluginManager()->setInvokableClass('navigationMenu', 'Application\View\Helper\NavigationMenu');
  13.  
  14.                 return $helper;
  15.              }
  16.          )
  17.      );
  18. }
  19. ...
esto es importante porque "pisa" el que carga por defecto Zend ;).

NavigationMenu
Código PHP:
Ver original
  1. namespace Application\View\Helper;
  2.  
  3. use Zend\View\Helper\Navigation\Menu;
  4. use Zend\Navigation\Page\AbstractPage;
  5.  
  6. class NavigationMenu extends Menu
  7. {...}

view.phtml
Código HTML:
Ver original
  1. <?php echo $this->navigation('navigation')->navigationMenu()->renderMenu(); ?>

tu lo tienes así y no te funciona ?

PD: que no decaiga Uncontroled_Duck :)

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #11 (permalink)  
Antiguo 27/09/2012, 03:23
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Hola masterpuppet,

Ayer lo probé varias veces, y seguía dándome error. Class not found.

Cambié un par de cosas y nada. Así que lo cerré todo, y esta mañana mas descansado, lo he revisado todo detenidamente.

El tema es que carga el Helper de forma global, desde module/Application/src/View/Helper.

Y a pesar de que vi que tenías el namespace Application\View\Helper seguía probando con Navigation\View\Helper,

Así que nada, lo he sacado de module-dev y al ponerlo en module todo como la seda, perfecto!
Cita:
Iniciado por masterpuppet Ver Mensaje
NavigationMenu
Código PHP:
Ver original
  1. namespace Application\View\Helper;
  2. // lo tenía así: namespace Navigation\View\Helper;
  3.  
  4. use Zend\View\Helper\Navigation\Menu;
  5. use Zend\Navigation\Page\AbstractPage;
  6.  
  7. class NavigationMenu extends Menu
  8. {...}
Sería correcto añadir mas Helper's así?
Lo he probado y funciona, pero no se si es lo ideal.
Cita:
Iniciado por masterpuppet Ver Mensaje
Module.php
Código PHP:
Ver original
  1. ...
  2. public function getViewHelperConfig()
  3. {
  4.     return array(
  5.         'factories' => array(
  6.             'navigation' => function($pm) {
  7.                 $helper = new \Zend\View\Helper\Navigation;
  8.  
  9.                 $pm->injectRenderer($helper);
  10.  
  11.                 $helper->setServiceLocator($pm->getServiceLocator());
  12.                 $helper->getPluginManager()
  13.                        ->setInvokableClass('navigationMenu', 'Application\View\Helper\NavigationMenu');
  14.                 //Añadir otra más así sería correcto?
  15.                 $helper->getPluginManager()
  16.                        ->setInvokableClass('navigationBreadcrumbs', 'Application\View\Helper\NavigationBreadcrumbs');
  17.  
  18.                 return $helper;
  19.              }
  20.          )
  21.      );
  22. }
  23. ...
esto es importante porque "pisa" el que carga por defecto Zend ;).
Cita:
Iniciado por masterpuppet Ver Mensaje
[...]
PD: que no decaiga Uncontroled_Duck :)
[...]
Gracias.

Si no decae, pero es que a veces me deja así

Un saludo, y muchisimas gracias de nuevo por tu tiempo.
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight

Última edición por Uncontroled_Duck; 27/09/2012 a las 06:41 Razón: Corregir error de ortografía
  #12 (permalink)  
Antiguo 27/09/2012, 06:26
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Muy correcto pisar el por defecto no es, para mi es mas un "hack" que otra cosa, debería ser transparente a través del config como los view helpers(ojo, talves lo sea, no lo he mirado al 100%), de todas formas se puede obtener el por defecto y de esta forma no pisarlo, no es lo ideal pero me parece mejor solución, algo asi:

Código PHP:
Ver original
  1. public function onBootstrap($e)
  2. {
  3.    ...
  4.     $vhm = $e->getApplication()
  5.              ->getServiceManager()
  6.              ->get('ViewHelperManager');
  7.     $helper = $vhm->get('navigation');
  8.     $helper->getPluginManager()
  9.            ->setInvokableClass('navigationMenu', 'Application\View\Helper\NavigationMenu');
  10. }

quedar es algo normal, estamos hablando de state of the art en fw's PHP ;)

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #13 (permalink)  
Antiguo 28/09/2012, 04:29
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Bueno, pues adaptado queda.

No lo he probado a fondo, así que si lo prueban y da algún error, agradezco que lo comenten.

Compatible con la versión:
ZendFramework 2.0.2
Twitter Bootstrap 2.1.1
Nota: El menú desplegable no admite aún un submenú desplegable. Para la próxima que lo revise intento actualizar eso.

En el resto del post viene como adaptar el View Helper NavigationMenu

PD.: Lo pongo en varias partes por la limitación de caracteres.

NavigationMenu.php (Estructura)
Código PHP:
namespace ApplicationViewHelper;

use 
ZendViewHelperNavigationMenu;
use 
RecursiveIteratorIterator;
use 
ZendNavigationAbstractContainer;
use 
ZendNavigationPageAbstractPage;

/**
 * Agrega menús desplegables y/o iconos en los distintos menús del
 *  View Helper Menu de Navigation
 * 
 * Añade las propiedades 
 *      liclass
 *      iclass
 * 
 * Modifica la clase active
 *      Por defecto en Zend
 *      <li>
 *          <a class="active">link</a>
 *      </li>
 *      
 *      Con el View Helper NavigationMenu
 *      <li class="active">
 *          <a>link</a>
 *      </li>
 * 
 * Opciones personalizadas:
 *      Para iniciar un menú desplegable:
 *          'label'   => 'Dropdown',
 *          'liclass' => 'dropdown',
 *          'iclass'  => 'icon-name', //si se quiere poner un icono junto al enlace
 *          'class'   => 'dropdown-toggle',
 *          'uri'     => '/', //sin url
 *          'pages'   => array(array('pages'))
 * 
 *      Para añadir un separador vertical en el menú del header
 *          array(
 *              'label'   => '',
 *              'liclass' => 'divider-vertical',
 *              'uri'     => '',
 *          ),
 * 
 *      Para añadir un separador horizontal en un menu desplegable del menú del header
 *      Para añadir un separador horizontal en un menu vertical
 *          array(
 *              'label'   => '',
 *              'liclass' => 'divider',
 *              'uri'     => '',
 *          ),
 * 
 * @author ORD, alias Uncontroled Duck
 * @version bootstrap twitter 2.1.1
 * @version ZendFramework 2.0.3
 */
class NavigationMenu extends Menu
{
    
/**
     * Returns an HTML string containing an 'a' element for the given page if
     * the page's href is not empty, and a 'span' element if it is empty
     *
     * Overrides {@link AbstractHelper::htmlify()}.
     *
     * @param  AbstractPage $page   page to generate HTML for
     * @param bool $escapeLabel     Whether or not to escape the label
     * @return string               HTML string for the given page
     */
    
public function htmlify(AbstractPage $page$escapeLabel true)
    {
        
//...
    
}

    
/**
     * Renders a normal menu (called from {@link renderMenu()})
     *
     * @param  AbstractContainer         $container    container to render
     * @param  string                    $ulClass      CSS class for first UL
     * @param  string                    $indent       initial indentation
     * @param  int|null                  $minDepth     minimum depth
     * @param  int|null                  $maxDepth     maximum depth
     * @param  bool                      $onlyActive   render only active branch?
     * @param  bool                      $escapeLabels Whether or not to escape the labels
     * @return string
     */
    
protected function renderNormalMenu(AbstractContainer $container$ulClass$indent$minDepth$maxDepth$onlyActive$escapeLabels)
    {
        
//...
    
}

__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #14 (permalink)  
Antiguo 28/09/2012, 04:30
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Código PHP:
/**
 * Returns an HTML string containing an 'a' element for the given page if
 * the page's href is not empty, and a 'span' element if it is empty
 *
 * Overrides {@link AbstractHelper::htmlify()}.
 *
 * @param  AbstractPage $page   page to generate HTML for
 * @param bool $escapeLabel     Whether or not to escape the label
 * @return string               HTML string for the given page
 */
public function htmlify(AbstractPage $page$escapeLabel true)
{
    
// get label and title for translating
    
$label $page->getLabel();
    
$title $page->getTitle();

    
// translate label and title?
    
if( null !== ($translator $this->getTranslator()) )
    {
        
$textDomain $this->getTranslatorTextDomain();
        if( 
is_string($label) && !empty($label) )
        {
            
$label $translator->translate($label$textDomain);
        }
        if( 
is_string($title) && !empty($title) )
        {
            
$title $translator->translate($title$textDomain);
        }
    }

    
// get attribs for element
    
$attribs = array(
        
'id' => $page->getId(),
        
'title' => $title,
        
'class' => $page->getClass()
    );

    
// does page have a href?
    
$href $page->getHref();
    if( 
$href )
    {
        
$element 'a';
        
$attribs['href'] = $href;
        
$attribs['target'] = $page->getTarget();
    }
    else
    {
        
$element 'span';
    }

    
// ***************** THESE ARE NEW LINES *************** //
    
if( $element === 'span' )
    {
        return 
$this->view->escapeHtml($label);
    }

    
$customProperties $page->getCustomProperties();
    if( 
$page->getClass() == 'dropdown-toggle' )
    {
        
//inserta un icono mediante el tag <iclass>icon-name</iclass>
        
if( isset($customProperties['iclass']) )
        {
            return 
'<' $element ' data-toggle="dropdown" ' $this->htmlAttribs($attribs) . '>'
                    
'<i class="' $customProperties['iclass'] . '"></i> '
                    
$this->view->escapeHtml($label)
                    . 
'<b class="caret"></b>'
                    
'</' $element '>';
        }

        return 
'<' $element ' data-toggle="dropdown" ' $this->htmlAttribs($attribs) . '>'
                
$this->view->escapeHtml($label)
                . 
' <b class="caret"></b>'
                
'</' $element '>';
    }
    elseif( isset(
$customProperties['iclass']) )
    {
        return 
'<' $element $this->htmlAttribs($attribs) . '>'
                    
'<i class="' $customProperties['iclass'] . '"></i> '
                    
$this->view->escapeHtml($label)
                    . 
'</' $element '>';
    }
    
// ***************** END OF NEW STUFF *************** //

    
$html '<' $element $this->htmlAttribs($attribs) . '>';
    if( 
$escapeLabel === true )
    {
        
$escaper $this->view->plugin('escapeHtml');
        
$html .= $escaper($label);
    }
    else
    {
        
$html .= $label;
    }
    
$html .= '</' $element '>';

    return 
$html;

__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #15 (permalink)  
Antiguo 28/09/2012, 04:31
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Código PHP:
/**
 * Renders a normal menu (called from {@link renderMenu()})
 *
 * @param  AbstractContainer         $container    container to render
 * @param  string                    $ulClass      CSS class for first UL
 * @param  string                    $indent       initial indentation
 * @param  int|null                  $minDepth     minimum depth
 * @param  int|null                  $maxDepth     maximum depth
 * @param  bool                      $onlyActive   render only active branch?
 * @param  bool                      $escapeLabels Whether or not to escape the labels
 * @return string
 */
protected function renderNormalMenu(AbstractContainer $container$ulClass$indent$minDepth$maxDepth$onlyActive$escapeLabels)
{
    
$html '';

    
// find deepest active
    
$found $this->findActive($container$minDepth$maxDepth);
    if( 
$found )
    {
        
$foundPage $found['page'];
        
$foundDepth $found['depth'];
    }
    else
    {
        
$foundPage null;
    }

    
// create iterator
    
$iterator = new RecursiveIteratorIterator($container,
                    
RecursiveIteratorIterator::SELF_FIRST);
    if( 
is_int($maxDepth) )
    {
        
$iterator->setMaxDepth($maxDepth);
    }

    
// iterate container
    
$prevDepth = -1;
    foreach( 
$iterator as $page )
    {
        
$depth $iterator->getDepth();
        
$isActive $page->isActive(true);
        if( 
$depth $minDepth || !$this->accept($page) )
        {
            
// page is below minDepth or not accepted by acl/visibility
            
continue;
        }
        elseif( 
$onlyActive && !$isActive )
        {
            
// page is not active itself, but might be in the active branch
            
$accept false;
            if( 
$foundPage )
            {
                if( 
$foundPage->hasPage($page) )
                {
                    
// accept if page is a direct child of the active page
                    
$accept true;
                }
                elseif( 
$foundPage->getParent()->hasPage($page) )
                {
                    
// page is a sibling of the active page...
                    
if( !$foundPage->hasPages() ||
                            
is_int($maxDepth) && $foundDepth $maxDepth )
                    {
                        
// accept if active page has no children, or the
                        // children are too deep to be rendered
                        
$accept true;
                    }
                }
            }

            if( !
$accept )
            {
                continue;
            }
        }

        
// make sure indentation is correct
        
$depth -= $minDepth;
        
$myIndent $indent str_repeat('        '$depth);

        if( 
$depth $prevDepth )
        {
            
// start new ul tag
            
if( $ulClass && $depth == )
            {
                
$ulClass ' class="' $ulClass '"';
            }
            else
            {
                
// ***************** THESE ARE NEW LINES *************** //
                
$ulClass ' class="dropdown-menu"';
                
// ***************** END OF NEW STUFF *************** //
                // render lu tag (ORGINAL LINE REMOVED)
                //$ulClass = '';
            
}
            
$html .= $myIndent '<ul' $ulClass '>' self::EOL;
        }
        elseif( 
$prevDepth $depth )
        {
            
// close li/ul tags until we're at current depth
            
for( $i $prevDepth$i $depth$i-- )
            {
                
$ind $indent str_repeat('        '$i);
                
$html .= $ind '    </li>' self::EOL;
                
$html .= $ind '</ul>' self::EOL;
            }
            
// close previous li tag
            
$html .= $myIndent '    </li>' self::EOL;
        }
        else
        {
            
// close previous li tag
            
$html .= $myIndent '    </li>' self::EOL;
        }

        
// ***************** THESE ARE NEW LINES *************** //
        
$liMyClass $page->get('liclass') ? $page->liclass '';

        if( 
$isActive )
        {
            
$liClass ' class="active' . (($liMyClass) ? ' ' $liMyClass '') . '" ';
        }
        else
        {
            
$liClass $liMyClass " class=\"$liMyClass\" " '';
        }

        
// ***************** END OF NEW STUFF *************** //
        // render li tag and page
        //$liClass = $isActive ? ' class="active"' : '';

        
$html .= $myIndent '    <li' $liClass '>' self::EOL
                
$myIndent '        ' $this->htmlify($page$escapeLabels) . self::EOL;

        
// store as previous depth for next iteration
        
$prevDepth $depth;
    }

    if( 
$html )
    {
        
// done iterating container; close open ul/li tags
        
for( $i $prevDepth 1$i 0$i-- )
        {
            
$myIndent $indent str_repeat('        '$i 1);
            
$html .= $myIndent '    </li>' self::EOL
                    
$myIndent '</ul>' self::EOL;
        }
        
$html rtrim($htmlself::EOL);
    }

    return 
$html;

__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #16 (permalink)  
Antiguo 28/09/2012, 04:32
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Ejemplo de un menú Navigation
Código PHP:
'navigation' => array(
        
// The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
        
'default' => array(
            
// And finally, here is where we define our page hierarchy
            
array(
                
'label'      => 'Navigation',
                
'route'     => 'home',
                
'controller' => 'index',
                
'action'     => 'index',
                
'pages'      => array(
                    array(
                        
'label'      => 'ApplicationTopMenu',
                        
'route'     => 'navigation',
                        
'controller' => 'index',
                        
'action'     => 'index',
                        
'pages'      => array(
                            array(
                                
'label'  => 'Home',
                                
'iclass' => 'icon-home',
                                
'route'  => 'home',
                            ),
                            array(
                                
'label'      => 'Navigation',
                                
'route'     => 'navigation',
                            ),
                            array(
                                
'label'      => 'System Requirements',
                                
'uri'     => '/',
                            ),
                            array(
                                
'label'   => '',
                                
'liclass' => 'divider-vertical',
                                
'uri'     => '',
                            ),
                            array(
                                
'label'      => 'Dropdown',
                                
'liclass'    => 'dropdown',
                                
'iclass'     => 'icon-book',
                                
'class'      => 'dropdown-toggle',
                                
'uri'     => '/',
                                
'pages'      => array(
                                    array(
                                        
'label' => 'Drop1',
                                        
'uri'   => '/',
                                    ),
                                    array(
                                        
'label' => 'Drop2',
                                        
'uri'   => '/',
                                    ),
                                    array(
                                        
'label'   => '',
                                        
'liclass' => 'divider',
                                        
'uri'     => '',
                                    ),
                                    array(
                                        
'label'  => 'Drop3',
                                        
'iclass' => 'icon-book',
                                        
'uri'    => '/',
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ), 
Ejemplo de un menú header con dropdown:
Código PHP:
<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </a>
            <!--a class="brand" href="#">ga</a-->
            <div class="nav-collapse">
                <?php
                $label 
$this->navigation('navigation')->findOneByLabel('ApplicationTopMenu');
                
$options = array('ulClass' => 'nav');
                echo 
$this->navigation()->navigationMenu()->renderMenu($label$options);
                
?>
            </div><!--/.nav-collapse -->
        </div>
    </div>
</div>
Ejemplo de un menú vertical:
Para ver más aspectos revisar la doc css de bootstrap twitter.
Código PHP:
<div class="row">
    <div class="span3">
            <?php
            $label 
$this->navigation('navigation')->findOneByLabel('ApplicationTopMenu');
            
$options = array('ulClass' => 'nav nav-tabs nav-stacked');
            
?>
            <?php echo $this->navigation('navigation')
                            ->
navigationMenu()              //view helper
                            //->setOnlyActiveBranch(false)  //Rendering only the active branch of a menu
                            //->setRenderParents(false)     //Rendering only the active branch of a menu with maximum depth and no parents
                            //->setMaxDepth(0)              //profuncidad de submenus or MinDepth
                            
->renderMenu($label$options); ?>
    </div>
</div>
PD.: Lógicamente, cualquier mejora es bienvenida.

Saludos,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #17 (permalink)  
Antiguo 28/09/2012, 06:52
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Zf2 Como Crear View Helper Navigation

Veo que estas con TB, talves te pueda interesar https://github.com/mwillbanks/ZfcTwitterBootstrap, y si compruebas los pull request's te vas a encontrar con algo familiar https://github.com/mwillbanks/ZfcTwi...otstrap/pull/4 :P

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #18 (permalink)  
Antiguo 28/09/2012, 08:25
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 13 años
Puntos: 261
Respuesta: Zf2 Como Crear View Helper Navigation

Cita:
Iniciado por masterpuppet Ver Mensaje
Veo que estas con TB, talves te pueda interesar https://github.com/mwillbanks/ZfcTwitterBootstrap, y si compruebas los pull request's te vas a encontrar con algo familiar https://github.com/mwillbanks/ZfcTwi...otstrap/pull/4 :P

Saludos.
No lo había visto

Se ve bastante completo. Lo miraré más a fondo.

Gracias,

Un saludo,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight

Etiquetas: helper, navigation, view, zf2
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:07.