Foros del Web » Programando para Internet » PHP » Zend »

[SOLUCIONADO] Paginator Zend Framework 2.0 beta

Estas en el tema de Paginator Zend Framework 2.0 beta en el foro de Zend en Foros del Web. Hola que tal, estoy siguiendo con el tutorial de Zend framework 2.0 beta 2 y todo funciona bien. Pero aun sigo sin entender como maneja ...

  #1 (permalink)  
Antiguo 15/02/2012, 11:44
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Paginator Zend Framework 2.0 beta

Hola que tal, estoy siguiendo con el tutorial de Zend framework 2.0 beta 2 y todo funciona bien. Pero aun sigo sin entender como maneja la configuración esta versión. Estoy viendo como adaptarle al ejemplo un paginador básico:

Código PHP:
Ver original
  1. $data = $this->albumTable->fetchAll();
  2.        
  3. //PaginationControl::setDefaultViewPartial('views/album/items.phtml');
  4.        
  5. $paginator = Paginator::factory($data);
  6. $paginator->setDefaultItemCountPerPage(5);
  7.        
  8. return array(
  9.             'albums' => $paginator
  10. );

Me muestra 5 elementos como debería, pero a la hora de imprimir los controles de paginación en la vista me sale el error:

Cita:
Warning: No view partial provided and no default set
al colocar la línea:

Código PHP:
Ver original
  1. PaginationControl::setDefaultViewPartial('views/album/items.phtml');

El error cambia a:

Cita:
Warning: No view script directory set; unable to determine location for view script
Mi duda es como establecer el directorio script view para que sepa en donde tengo mi vista para el paginador.

Gracias, saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #2 (permalink)  
Antiguo 15/02/2012, 12:12
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: Paginator Zend Framework 2.0 beta

No he mirado como funciona esta versión de Zend, pero supongo que el path es el que declaras en el di, probaste así ?:

Código PHP:
Ver original
  1. PaginationControl::setDefaultViewPartial('/album/items.phtml');

Zend va a pagar(creo que de echo ya lo esta haciendo) un precio alto por demorar tanto en poner esto en producción.
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 15/02/2012, 12:24
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Pues he probado con todas las rutas y no da que rico que estuviera listo.

Esta es mi configuración, que faltaría en el di?

Código PHP:
Ver original
  1. <?php
  2.  
  3. return array (
  4.  
  5.     'home' => array(
  6.         'type' => 'Zend\Mvc\Router\Http\Literal',
  7.         'options' => array(
  8.             'route' => '/',
  9.             'defaults' => array(
  10.                 'controller' => 'album',
  11.                 'action' => 'index',
  12.             ),
  13.          ),
  14.       ),
  15.  
  16.     'di' => array (
  17.         'instance' => array (
  18.             'alias' => array (
  19.                 'album' => 'Album\Controller\AlbumController',
  20.             ),
  21.        
  22.             'Album\Controller\AlbumController' => array (
  23.                 'parameters' => array (
  24.                    'albumTable' => 'Album\Model\AlbumTable'      
  25.                 )
  26.             ),
  27.            'Album\Model\AlbumTable' => array (
  28.                'parameters' => array (
  29.                     'config' => 'Zend\Db\Adapter\PdoMysql'
  30.                
  31.                )),
  32.        
  33.         'Zend\Db\Adapter\PdoMysql' => array (
  34.             'parameters' => array (
  35.                 'config' => array (
  36.                     'host' => 'localhost',
  37.                     'username' => 'root',
  38.                     'password' => '12345',
  39.                     'dbname' => 'test'
  40.                 )
  41.             )
  42.         ),
  43.        
  44.             'Zend\View\PhpRenderer' => array (
  45.                 'parameters' => array (
  46.                      'options' => array (
  47.                          'script_paths' => array (
  48.                              'album' => __DIR__ . '/../views'
  49.                          )
  50.                      )  
  51.                 )
  52.             )
  53.         )    
  54.     )
  55.  
  56. );
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #4 (permalink)  
Antiguo 15/02/2012, 12:59
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Gracias, si quiero hacerlo desde el controller

Código PHP:
Ver original
  1. public function indexAction()
  2.     {
  3.        
  4.         $data = $this->albumTable->fetchAll();
  5.        
  6.         PaginationControl::setDefaultViewPartial('/album/items.phtml');
  7.        
  8.         $paginator = Paginator::factory($data);
  9.         $paginator->setDefaultItemCountPerPage(5);
  10.        
  11.         return array(
  12.             'albums' => $paginator
  13.         );
  14.     }

Ahora si lo hago desde la vista:

Código PHP:
Ver original
  1. echo $this->paginationControl(
  2.     $albums, 'Sliding', 'album/items.phtml'
  3. );

Me salen los controles como debería pero a la vez me da este error:

Cita:
Route with name "" not found
Pero lo que quiero es saber como hacerlo desde el controlador.

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #5 (permalink)  
Antiguo 15/02/2012, 15:13
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: Paginator Zend Framework 2.0 beta

El problema seguramente sea que el view del paginator y el de di no son el mismo, el del paginator probablemente no tenga las rutas seteadas, por eso el error.
Testea con algo así a ver si el error persiste:

Código PHP:
Ver original
  1. ...
  2. $paginator = Paginator::factory($data);
  3. $paginator->setDefaultItemCountPerPage(5);
  4. $paginator->setView($this->locator->get('view'));
  5. ...

En teoría deberías definir y setear las dependencias del paginator en el di.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #6 (permalink)  
Antiguo 15/02/2012, 15:28
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Cita:
Iniciado por masterpuppet Ver Mensaje
En teoría deberías definir y setear las dependencias del paginator en el di.
Si esa es mi duda, no se como setearlas.

Colocando esa línea me aparecen ya los números con los controles acompañado de este error:

Cita:
Route with name "" not found
y este otro:

Cita:
Warning: explode() expects parameter 2 to be string, array given in library\Zend\Mvc\Router\Http\TreeRouteStack.php
No es tan fácil como en Zend 1

Gracias masterpuppet
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #7 (permalink)  
Antiguo 15/02/2012, 16:23
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

Prueba agregar a tu DI así:
Código PHP:
Ver original
  1. 'Zend\View\TemplatePathStack' => array('parameters' => array(
  2.                 'paths'  => array(
  3.                     'albumns' => __DIR__ . '/../views',
  4.                 ),
  5.             )),

En teoría debería de ser el mismo view, ya que se renderea usando un plugin del view actual, o sea es la misma instancia...
  #8 (permalink)  
Antiguo 15/02/2012, 16:34
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Si lo coloco en el di me sale este error, como que me modifica los otros paths:

Cita:
Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Script "layout/layout.phtml" not found in path (C:\Zend\Apache2\htdocs\zf\module\Album\config/../views\)' in C:\Zend\ZendServer\share\zf2\library\Zend\View\Tem platePathStack.php:291 Stack trace: #0
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #9 (permalink)  
Antiguo 15/02/2012, 17:15
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

¿Como tienes creado tu partial?
  #10 (permalink)  
Antiguo 15/02/2012, 17:31
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Tomé uno de los que usaba en ZF1

Código PHP:
Ver original
  1. <?php if ($this->pageCount): ?>
  2. <div class="paginationControl">
  3. <?php echo $this->firstItemNumber; ?> - <?php echo $this->lastItemNumber; ?>
  4. of <?php echo $this->totalItemCount; ?>
  5.  
  6. <!-- First page link -->
  7. <?php if (isset($this->previous)): ?>
  8.   <a href="<?php echo $this->url(array('page' => $this->first)); ?>">
  9.     First
  10.   </a> |
  11. <?php else: ?>
  12.   <span class="disabled">First</span> |
  13. <?php endif; ?>
  14.  
  15. <!-- Previous page link -->
  16. <?php if (isset($this->previous)): ?>
  17.   <a href="<?php echo $this->url(array('page' => $this->previous)); ?>">
  18.     &lt; Previous
  19.   </a> |
  20. <?php else: ?>
  21.   <span class="disabled">&lt; Previous</span> |
  22. <?php endif; ?>
  23.  
  24. <!-- Next page link -->
  25. <?php if (isset($this->next)): ?>
  26.   <a href="<?php echo $this->url(array('page' => $this->next)); ?>">
  27.     Next &gt;
  28.   </a> |
  29. <?php else: ?>
  30.   <span class="disabled">Next &gt;</span> |
  31. <?php endif; ?>
  32.  
  33. <!-- Last page link -->
  34. <?php if (isset($this->next)): ?>
  35.   <a href="<?php echo $this->url(array('page' => $this->last)); ?>">
  36.     Last
  37.   </a>
  38. <?php else: ?>
  39.   <span class="disabled">Last</span>
  40. <?php endif; ?>
  41.  
  42. </div>
  43. <?php endif; ?>

El error anterior se solucionó con lo que me dió masterpuppet

Código PHP:
Ver original
  1. $paginator->setView($this->locator->get('view'))

con eso ya encuentra el items.phtml

Ahora me dice que:

Cita:
Warning: Route with name "" not found in \library\Zend\Paginator\Paginator.php on line 424
A que ruta se refiere y como se setea? algo más del di?

También me falta decirle en donde tiene que empezar, pero de ZF1 a ZF2 hay mucha diferencia. En ZF1 le decia:

Código PHP:
Ver original
  1. if ($this->_hasParam('page')) {
  2.      $paginator->setCurrentPageNumber($this->_getParam('page'));
  3. }

En el ZF2 no sé como sería.

Gracias GatorV
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #11 (permalink)  
Antiguo 15/02/2012, 18:03
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

El problema es que el url ViewHelper, ha cambiado, los parámetros ahora son así:
Código PHP:
Ver original
  1. /**
  2.      * Generates an url given the name of a route.
  3.      *
  4.      * @see    Zend\Mvc\Router\Route::assemble()
  5.      * @param  string  $name               Name of the route
  6.      * @param  array   $params             Parameters for the link
  7.      * @param  array   $options            Options for the route
  8.      * @param  boolean $reuseMatchedParams Whether to reuse matched parameters
  9.      * @return string Url                  For the link href attribute
  10.      * @throws Exception\RuntimeException  If no RouteStack was provided
  11.      * @throws Exception\RuntimeException  If no RouteMatch was provided
  12.      * @throws Exception\RuntimeException  If RouteMatch didn't contain a matched route name
  13.      */
  14.     public function __invoke($name = null, array $params = array(), array $options = array(), $reuseMatchedParams = false)

Es por eso que te marca el error, por otro lado desde el DI podrías indicarle usar el mismo view, usando algo así:
Código PHP:
Ver original
  1. 'Zend\Paginator\Paginator' => array(
  2.        'view' => 'view' // alias
  3. )

Saludos.
  #12 (permalink)  
Antiguo 15/02/2012, 18:21
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Creo que ya pude avanzar. En vez de colocar:

Código PHP:
Ver original
  1. $paginator->setView($this->locator->get('view'));

coloqué

Código PHP:
Ver original
  1. $view = new PhpRenderer();
  2. $view->resolver()->addPath(__DIR__ . '/paginator');
  3. PaginationControl::setDefaultViewPartial('items.phtml');

Ahora no me sale ningún error, pero tampoco me muestra los enlaces de anterior y siguiente (Esto es lo que menos importa ahora). Hice la prueba:

Código PHP:
Ver original
  1. $paginator->setCurrentPageNumber(1);

y me muestra correctamente la página 1, si lo cambio a 2 me muestra la 2. Todo Ok.

Ahora me quedan 2 dudas...

1. Como le digo a $view->resolver()->addPath(__DIR__ . '/paginator') que el Partial está en la carpeta views y no en controller como lo tengo ahora.

Si imprimo __DIR__ me da

Cita:
C:\Zend\Apache2\htdocs\zf\module\Album\src\Album\C ontroller
Como me devuelvo hasta

Cita:
C:\Zend\Apache2\htdocs\zf\module\Album\views\...
2. Como hago para setear setCurrentPageNumber en el controller para que sea dinámico. En ZF1 hacía:

Código PHP:
Ver original
  1. if ($this->_hasParam('page')) {
  2.      $paginator->setCurrentPageNumber($this->_getParam('page'));
  3. }

Me pondré a leer las clases a ver como se mueve todo eso.

Les agradezco la ayuda y la paciencia en este mundo tan oscuro todavía.

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #13 (permalink)  
Antiguo 15/02/2012, 18:27
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: Paginator Zend Framework 2.0 beta

No se como funciona exactamente el di, pero creo que necesita instanciar por medio de factory el paginator, para luego "llamar" al setView con el view del di, la parte del paginator es sencilla, la parte de setear la vista es la que no me cuadra, @GatorV si tenes algún ejemplo funcionando seria genial, es muy potente el DI pero es bastante mas entreverado que el de SF2.

@andres probaste con:

Código PHP:
Ver original
  1. $view->resolver()->addPath(__DIR__ . '/../../paginator');
__________________
http://es.phptherightway.com/
thats us riders :)
  #14 (permalink)  
Antiguo 15/02/2012, 18:35
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Cita:
Iniciado por masterpuppet Ver Mensaje
@andres probaste con:

Código PHP:
Ver original
  1. $view->resolver()->addPath(__DIR__ . '/../../paginator');
Gracias masterpuppet, lo pude solucionar con:

Código PHP:
Ver original
  1. $view->resolver()->addPath(__DIR__ . '/../../../views/paginator');

Ahora solo me falta el tema del controller, como setear setCurrentPageNumber para poder moverme entre páginas. Actualmente me sale así:

1 - 5 of 11 First | < Previous |

Sin ningún enlace.

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #15 (permalink)  
Antiguo 15/02/2012, 18:48
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: Paginator Zend Framework 2.0 beta

Debería ser algo así:

Código PHP:
Ver original
  1. $paginator->setCurrentPageNumber($this->request->query()->get('page', 1));
__________________
http://es.phptherightway.com/
thats us riders :)
  #16 (permalink)  
Antiguo 15/02/2012, 19:04
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Gracias masterpuppet, pero no tengo como verificar que sirva. No me quieren salir los enlaces para darle siguiente en los controles del paginador.

Mi action quedó así:

Código PHP:
Ver original
  1. public function indexAction()
  2.     {
  3.         $data = $this->albumTable->fetchAll();
  4.        
  5.         $view = new PhpRenderer();
  6.         $view->resolver()->addPath(__DIR__ . '/../../../views/paginator');
  7.         PaginationControl::setDefaultViewPartial('items.phtml');
  8.        
  9.         $paginator = Paginator::factory($data);
  10.         $paginator->setDefaultItemCountPerPage(5);
  11.         $paginator->setView($view);
  12.        
  13.         if ($this->request->query()->get('page')) {
  14.             $paginator->setCurrentPageNumber($this->request->query()->get('page', 1));
  15.         }
  16.        
  17.         return array(
  18.             'albums' => $paginator
  19.         );
  20. }

Depronto sabes porque no me muestra los enlaces? Si imprimo en el partial por ejemplo:

Código PHP:
Ver original
  1. <?php echo $this->url(array('page' => $this->next)); ?>

Me sale:

Cita:
Warning: No RouteStack instance provided in \library\Zend\Paginator\Paginator.php on line 424
Algo más me falta por hacer?
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #17 (permalink)  
Antiguo 15/02/2012, 19:24
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: Paginator Zend Framework 2.0 beta

GatorV te mostro el cambio, el primer parámetro es el router

Código PHP:
Ver original
  1. <?php echo $this->url('default', array('page' => $this->next)); ?>

Ten en cuenta que tienes que agregar el router a tu config y una sugerencia, no es necesario controlar si page esta definido, el 1 como segundo parámetro del get setea ese valor por defecto, osea si no hay pagina seleccionada setea la primera pagina ;)


Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #18 (permalink)  
Antiguo 15/02/2012, 19:54
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

Exacto, y no, ahorita no tengo ningún ejemplo pero igual en un rato me pondré a cocinar un ejemplo ya que me interesó mucho el tema, ya que viendo el application veo que crean el view con un alías:
Código PHP:
Ver original
  1. return array(
  2.     'di'                    => array(
  3.         'instance' => array(
  4.             'alias' => array(
  5.                 'index' => 'Application\Controller\IndexController',
  6.                 'error' => 'Application\Controller\ErrorController',
  7.                 'view'  => 'Zend\View\PhpRenderer',
  8.             ),
  9.            
  10.             // Setup the PhpRenderer
  11.             'Zend\View\PhpRenderer' => array(
  12.                 'parameters' => array(
  13.                     'resolver' => 'Zend\View\TemplatePathStack',
  14.                     'options'  => array(
  15.                         'script_paths' => array(
  16.                             'application' => __DIR__ . '/../view',
  17.                         ),
  18.                     ),
  19.                 ),
  20.             ),

Por lo que es probable que puedas indicarle al Paginator que use esa instancia sin tener que este explicitamente definido como tiene ahorita el controller.

Saludos.
  #19 (permalink)  
Antiguo 15/02/2012, 20:22
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

No pues que les digo... Me perdí completamente. No pude hacer que me muestre los enlaces, así me quedó:

1 - 5 of 11 First | < Previous |

Buscaré más información a ver si logró armar el paginador. Muchas gracias a los dos.

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #20 (permalink)  
Antiguo 15/02/2012, 21:22
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
¿Como dejaste el script de paginación?
  #21 (permalink)  
Antiguo 15/02/2012, 21:26
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Controlador

Código PHP:
Ver original
  1. public function indexAction()
  2.     {
  3.         $data = $this->albumTable->fetchAll();
  4.  
  5.         $view = new PhpRenderer();
  6.         $view->resolver()->addPath(__DIR__ . '/../../../views/paginator');
  7.  
  8.         PaginationControl::setDefaultViewPartial('items.phtml');
  9.        
  10.         $paginator = Paginator::factory($data);
  11.         $paginator->setDefaultItemCountPerPage(5);
  12.         $paginator->setView($view);
  13.        
  14.         $paginator->setCurrentPageNumber($this->request->query()->get('page', 1));
  15.        
  16.         return array(
  17.             'albums' => $paginator
  18.         );
  19.     }

la vista:

Código PHP:
Ver original
  1. <?php if ($this->pageCount): ?>
  2. <div class="paginationControl">
  3. <?php echo $this->firstItemNumber; ?> - <?php echo $this->lastItemNumber; ?>
  4.  of <?php echo $this->totalItemCount; ?>
  5.  
  6. <!-- First page link -->
  7. <?php if (isset($this->previous)): ?>
  8.   <a href="<?php echo $this->url('default', array('page' => $this->first)); ?>">
  9.     First
  10.   </a> |
  11. <?php else: ?>
  12.   <span class="disabled">First</span> |
  13. <?php endif; ?>
  14.  
  15. <!-- Previous page link -->
  16. <?php if (isset($this->previous)): ?>
  17.   <a href="<?php echo $this->url('default', array('page' => $this->previous)); ?>">
  18.     &lt; Previous
  19.   </a> |
  20. <?php else: ?>
  21.   <span class="disabled">&lt; Previous</span> |
  22. <?php endif; ?>
  23.  
  24. <!-- Next page link -->
  25. <?php if (isset($this->next)): ?>
  26.   <a href="<?php echo $this->url('default', array('page' => $this->next)); ?>">
  27.     Next &gt;
  28.   </a> |
  29. <?php else: ?>
  30.   <span class="disabled">Next &gt;</span> |
  31. <?php endif; ?>
  32.  
  33. <!-- Last page link -->
  34. <?php if (isset($this->next)): ?>
  35.   <a href="<?php echo $this->url('default', array('page' => $this->last)); ?>">
  36.     Last
  37.   </a>
  38. <?php else: ?>
  39.   <span class="disabled">Last</span>
  40. <?php endif; ?>
  41.  
  42. </div>
  43. <?php endif; ?>

Edit: Todo el problema debe ser relacionado con esto:

Cita:
Warning: No RouteStack instance provided
Y en lo demás ya no le hice cambios (es lo mismo del tutorial), quedó sin mostrar enlaces.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP

Última edición por andresdzphp; 15/02/2012 a las 22:06
  #22 (permalink)  
Antiguo 16/02/2012, 13:39
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

Acabo de hacer una pequeña prueba y no tuve que hacer muchos cambios, el DI:
Código PHP:
Ver original
  1. 'di' => array(
  2.         'instance' => array(
  3.             'alias' => array(
  4.                 'album-list' => 'Album\Controller\ListController'
  5.             ),
  6.             'Album\Controller\ListController' => array (
  7.                 'parameters' => array (
  8.                    'albumTable' => 'Album\Model\DbTable\AlbumTable'
  9.                 )
  10.             ),
  11.             'Album\Model\DbTable\AlbumTable' => array (
  12.                 'parameters' => array (
  13.                     'config' => 'Zend\Db\Adapter\PdoMysql'
  14.                 )
  15.             ),
  16.             'Zend\Db\Adapter\PdoMysql' => array (
  17.                 'parameters' => array (
  18.                     'config' => array (
  19.                         'host' => 'localhost',
  20.                         'username' => 'root',
  21.                         'password' => 'mypwd',
  22.                         'dbname' => 'test'
  23.                     )
  24.                 )
  25.             ),
  26.             'Zend\View\PhpRenderer' => array(
  27.                 'parameters' => array(
  28.                     'options'  => array(
  29.                         'script_paths' => array(
  30.                             'Album' => __DIR__ . '/../views',
  31.                         ),
  32.                     ),
  33.                 ),
  34.             ),
  35.             'Zend\Mvc\Router\RouteStack' => array(
  36.                 'parameters' => array(
  37.                     'routes' => array(
  38.                         'album-list' => array(
  39.                             'type'    => 'Zend\Mvc\Router\Http\Segment',
  40.                             'options' => array(
  41.                                 'route' => '/album[/:page]',
  42.                                 'constraints' => array(
  43.                                     'page' => '[0-9]+',
  44.                                 ),
  45.                                 'defaults' => array(
  46.                                     'controller' => 'album-list',
  47.                                     'action'     => 'index',
  48.                                     'page'       => 1
  49.                                 ),
  50.                             ),
  51.                         ),
  52.                     ),
  53.                 ),
  54.             ),
  55.         ),
  56.     ),

Controlador:
Código PHP:
Ver original
  1. public function indexAction()
  2.     {
  3.         $albums = $this->getAlbumTable()->fetchAll();
  4.         $matches = $this->getEvent()->getRouteMatch();
  5.         $nPage = $matches->getParam('page', 1);
  6.        
  7.         PaginationControl::setDefaultViewPartial('paginator.phtml');
  8.        
  9.         $paginator = Paginator::factory($albums);
  10.         $paginator->setDefaultItemCountPerPage(5);
  11.         $paginator->setCurrentPageNumber($nPage);
  12.        
  13.         return array('albums' => $paginator);
  14.     }

Vista:
Código PHP:
Ver original
  1. <h1>Albums</h1>
  2. <ul>
  3. <?php foreach ($this->albums as $album) { ?>
  4.     <li><?php echo $album->album_id; ?> - <?php echo $album->album; ?></li>
  5. <?php } ?>
  6. </ul>
  7. <?php echo $this->paginationControl($this->albums, 'Sliding'); ?>

Paginador:
Código PHP:
Ver original
  1. <?php if ($this->pageCount): ?>
  2. <div class="paginationControl">
  3. <?php echo $this->firstItemNumber; ?> - <?php echo $this->lastItemNumber; ?>
  4.  de <?php echo $this->totalItemCount; ?>
  5.  
  6. <!-- First page link -->
  7. <?php if (isset($this->previous)): ?>
  8.   <a href="<?php echo $this->url('album-list', array('page' => $this->first)); ?>">
  9.     Primero
  10.   </a> |
  11. <?php else: ?>
  12.   <span class="disabled">First</span> |
  13. <?php endif; ?>
  14.  
  15. <!-- Previous page link -->
  16. <?php if (isset($this->previous)): ?>
  17.   <a href="<?php echo $this->url('album-list', array('page' => $this->previous)); ?>">
  18.     &lt; Anterior
  19.   </a> |
  20. <?php else: ?>
  21.   <span class="disabled">&lt; Anterior</span> |
  22. <?php endif; ?>
  23.  
  24. <!-- Next page link -->
  25. <?php if (isset($this->next)): ?>
  26.   <a href="<?php echo $this->url('album-list', array('page' => $this->next)); ?>">
  27.     Siguiente &gt;
  28.   </a> |
  29. <?php else: ?>
  30.   <span class="disabled">Siguiente &gt;</span> |
  31. <?php endif; ?>
  32.  
  33. <!-- Last page link -->
  34. <?php if (isset($this->next)): ?>
  35.   <a href="<?php echo $this->url('album-list', array('page' => $this->last)); ?>">
  36.     Último
  37.   </a>
  38. <?php else: ?>
  39.   <span class="disabled">Último</span>
  40. <?php endif; ?>
  41.  
  42. </div>
  43. <?php endif; ?>
  #23 (permalink)  
Antiguo 16/02/2012, 14:01
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Excelente GatorV, funciona perfectamente. Yo si decía que faltaba algo relacionado con Warning: No RouteStack instance provided, pero no sabía realmente como armar estas configuraciones. Algún tip?

Muchas gracias
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #24 (permalink)  
Antiguo 16/02/2012, 14:13
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

Pues el problema del Warning: No RouteStack instance provided era porque estabas sobre-escribiendo el objeto View con uno en blanco jeje, sí te fijas el Application establece un router y lo pasa al url helper:
Código PHP:
Ver original
  1. $locator = $app->getLocator();
  2.         $view    = $locator->get('view');
  3.  
  4.         // Set up view helpers        
  5.         $view->plugin('url')->setRouter($app->getRouter());
  6.         $view->doctype()->setDoctype('HTML5');
  7.  
  8.         $basePath = $app->getRequest()->getBasePath();
  9.         $view->plugin('basePath')->setBasePath($basePath);

Así que solamente es usar el view por defecto y con eso no hay problema, realmente no se porque te daba error usar el paginador, ya que yo al construirlo de la manera que lo hice (sin darle nada extra al Paginator) funciona correctamente
  #25 (permalink)  
Antiguo 16/02/2012, 14:17
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Lo que no he entendido de ZF2 es como armar las configuraciones, no me acostumbro.

Código PHP:
Ver original
  1. 'Zend\Mvc\Router\RouteStack' => array(
  2.                 'parameters' => array(
  3.                     'routes' => array(
  4.                         'album-list' => array(
  5.                             'type'    => 'Zend\Mvc\Router\Http\Segment',
  6.                             'options' => array(
  7.                                 'route' => '/album[/:page]',
  8.                                 'constraints' => array(
  9.                                     'page' => '[0-9]+',
  10.                                 ),
  11.                                 'defaults' => array(
  12.                                     'controller' => 'album-list',
  13.                                     'action'     => 'index',
  14.                                     'page'       => 1
  15.                                 ),
  16.                             ),
  17.                         ),
  18.                     ),
  19.                 ),

En que te basas para crear esa configuración?
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #26 (permalink)  
Antiguo 16/02/2012, 14:28
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

En el Manual

http://packages.zendframework.com/do...c.routing.html
  #27 (permalink)  
Antiguo 16/02/2012, 14:37
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Voy a pegarle una leída a ver que más se me ocurre para el ejemplo.

Se aprendió bastante, gracias GatorV.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #28 (permalink)  
Antiguo 16/02/2012, 15:56
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: Paginator Zend Framework 2.0 beta

@andres es logico no saber el como, si el manual de Zend 2 es un chiste(y malo), toda la parte de di es manipulando objetos, y no tiene nada para hacerlo desde config.

@GatorV, no lo he probado, pera la idea de setDefaultViewPartial es no llamar a paginationControl, que pasa si haces ?:

Código PHP:
Ver original
  1. <?php echo $this->paginator; ?>

Yo creo que ese paginationControl hace trampas :P
__________________
http://es.phptherightway.com/
thats us riders :)
  #29 (permalink)  
Antiguo 16/02/2012, 16:04
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: Paginator Zend Framework 2.0 beta

Cita:
Iniciado por masterpuppet Ver Mensaje
Código PHP:
Ver original
  1. <?php echo $this->paginator; ?>

Yo creo que ese paginationControl hace trampas :P
Si se imprime el paginador:

Código PHP:
Ver original
  1. <?php echo $albums; ?>

Volvemos al error inicial:

Cita:
Warning: No view script directory set; unable to determine location for view script
El cual pude solucionar con:

Código PHP:
Ver original
  1. $view = new PhpRenderer();
  2. $view->resolver()->addPath(__DIR__ . '/../../../views/paginator');
  3. $paginator->setView($view);

Pero no sé como sería esto en el di.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #30 (permalink)  
Antiguo 16/02/2012, 17:18
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Paginator Zend Framework 2.0 beta

La cosa es que si haces directamente un <?php echo $this->albumns; ?> va a mandar al método render() del paginator el cual sí usa el paginationControl, pero en su propio "view", ya que como no tiene un view establecido, crea uno nuevo, es por eso que marca el error, para quitarlo y que todo funcione igual, hay que pasarle el view del locator:

Código PHP:
Ver original
  1. $paginator->setView($this->getLocator()->get('view'));

Con eso funciona igual, ahora hay que ver la forma de pasarle ese objeto view al Zend Paginator, como una dependencia, intenté esto:
Código PHP:
Ver original
  1. 'Zend\Paginator\Paginator' => array(
  2.                 'parameters' => array(
  3.                     'view' => 'Zend\View\PhpRenderer'
  4.                 )
  5.             ),

Pero no lo esta agarrando el DI, cuando en teoría sí debería de hacerlo...

Etiquetas: 2.0, beta, control, framework, pagination, paginator
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 00:13.