Zend Framework 2 Paginator Route 不起作用
Posted
技术标签:
【中文标题】Zend Framework 2 Paginator Route 不起作用【英文标题】:Zend Framework 2 Paginator Route not working 【发布时间】:2017-04-23 22:09:13 【问题描述】:我正在尝试让分页器拆分页面上显示的组数,但由于某种原因,当我尝试转到下一组数据或页面时,它默认返回到主布局和索引页面.我不知道为什么会这样,因为我以前做过,而且效果很好。
这是我的代码:
路线:
'groups' => array(
'type' => 'Segment',
'options' => array(
'route' => '/groups[/:action][/:id]',
'constraints' => array(
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Members\Controller\Groups',
'action' => 'index',
),
),
),
'paginator' => array(
'type' => 'Segment',
'options' => array(
'route' => '/groups/view-more/[page/:page]',
'constraints' => array(
'page' => '[0-9]*',
),
),
'defaults' => array(
'controller' => 'Members\Controller\Groups',
'action' => 'view-more',
),
),
控制器 -
public function viewmoreAction()
$paginator = new Paginator(new DbTableGateway($this->getGroupsTable()));
$page = 1;
if ($this->params()->fromRoute('page'))
$page = $this->params()->fromRoute('page');
$paginator->setCurrentPageNumber((int)$page);
$paginator->setItemCountPerPage(5);
return new ViewModel(array('paginator' => $paginator));
观点:
<div class="w3-row">
<div class="w3-col sm-12 w3-center">
<?php if (count($this->paginator) <= 0): ?>
<p class="w3-center">No more groups found</p>
<?php else: ?>
<div class="w3-responsive">
<table class="w3-table-all w3-card-4">
<thead>
<tr class="w3-white">
<th style="white-space: nowrap;">Group Id</th>
<th style="white-space: nowrap;">Group Name</th>
</tr>
</thead>
<?php
foreach ($this->paginator as $rows):
?>
<tr class="w3-hover-text-red w3-text-black">
<td><a href="<?php echo $this->url('members/groups', array('action' => 'group-home', 'id' => $rows['group_id'])); ?>">
<?php echo $rows['group_id']; ?>
</a></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<br><br>
<div class="w3-right">
<?php echo $this->paginationControl($this->pagination, 'Sliding', 'pagination.phtml', array('route' => 'members/paginator')); ?>
</div>
</div>
</div>
和分页器视图(不确定我是否需要包含这个,但我认为我应该)
<?php if ($this->pageCount): ?>
<div class="w3-bar">
<!-- 1st page link -->
<?php echo $this->firstItemNumber; ?> - <?php echo $this->lastItemNumber; ?> of <?php echo $this->totalItemCount; ?>
<?php if (isset($this->previous)): ?>
<a href="<?php echo $this->url($this->route, array('page' => $this->first)); ?>" class="w3-button">First</a> |
<?php else: ?>
<span class="w3-button w3-disabled">First</span> |
<?php endif; ?>
<!-- previous page link -->
<?php if (isset($this->previos)): ?>
<a href="<?php echo $this->url($this->route, array('page' => $this->previous)); ?>" class="w3-button">< Previous</a> |
<?php else: ?>
<span class="w3-button w3-disabled">Previous</span> |
<?php endif; ?>
<!-- next page link -->
<?php if (isset($this->next)): ?>
<a href="<?php echo $this->url($this->route, array('page' => $this->next)); ?>" class="w3-button">Next ></a> |
<?php else: ?>
<span class="w3-button w3-disabled">Next ></span> |
<?php endif; ?>
<!-- last page link -->
<?php if (isset($this->next)): ?>
<a href="<?php echo $this->url($this->route, array('page' => $this->last)); ?>" class="w3-button">Last</a>
<?php else: ?>
<span class="w3-button w3-disabled">Last</span>
<?php endif; ?>
</div>
Module.php 代码
class Module implements AutoloaderProviderInterface
public function getAutoloaderConfig()
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
public function getConfig()
return include __DIR__ . '/config/module.config.php';
public function onBootstrap(MvcEvent $e)
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkCredentials'));
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'configureLayout'));
public function checkCredentials(MvcEvent $e)
$matches = $e->getRouteMatch();
if (!$matches)
return $e;
$route = $matches->getMatchedRouteName();
if (0 !== strpos($route, 'members/') && $route !== 'members')
return $e;
$auth_service = $e->getApplication()->getServiceManager()->get('pblah-auth');
if (!$auth_service->hasIdentity())
$response = $e->getResponse();
$response->setStatusCode(302);
$response->getHeaders()
->addHeaderLine('Location', $e->getRouter()->assemble([], array('name' => 'home/member-login')));
$response->sendHeaders();
return $response;
return $e;
public function configureLayout(MvcEvent $e)
if ($e->getError())
return $e;
$request = $e->getRequest();
if (!$request instanceof Http\Request || $request->isXmlHttpRequest())
return $e;
$matches = $e->getRouteMatch();
if (!$matches)
return $e;
$app = $e->getParam('application');
$layout = $app->getMvcEvent()->getViewModel();
$controller = $matches->getParam('controller');
$module = strtolower(explode('\\', $controller)[0]);
if ('members' === $module)
$layout->setTemplate('layout/members');
public function getServiceConfig()
return array(
'factories' => array(
'Members\Module\EditProfileModel' => function ($sm)
$table_gateway = $sm->get('EditProfileService');
$profile = new EditProfileModel($table_gateway);
return $profile;
,
'EditProfileService' => function ($sm)
$db_adapter = $sm->get('Zend\Db\Adapter\Adapter');
$result_set_prototype = new ResultSet();
$result_set_prototype->setArrayObjectPrototype(new EditProfile());
return new TableGateway('profiles', $db_adapter, null, $result_set_prototype);
,
'Members\Model\ProfileModel' => function ($sm)
$table_gateway = $sm->get('ProfileService');
$profile = new ProfileModel($table_gateway, $sm->get('pblah-auth')->getIdentity());
return $profile;
,
'ProfileService' => function ($sm)
$db_adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new TableGateway('profiles', $db_adapter);
,
'Members\Model\GroupsModel' => function ($sm)
$table_gateway = $sm->get('GroupsService');
$group_model = new GroupsModel($table_gateway, $sm->get('pblah-auth')->getIdentity());
return $group_model;
,
'GroupsService' => function ($sm)
$db_adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new TableGateway('groups', $db_adapter);
),
);
我已经包含了三个屏幕截图(一个是关于分页器如何显示的,第二个是关于它如何重定向到错误页面的)
http://imgur.com/a/Cd269 - 第一
http://imgur.com/a/Yv3XL - 第二个
http://imgur.com/bOtDGYB - 第三
我希望这是足够的信息,如果没有,请告诉我,我会尽力补充更多。
谢谢!
更新 -
我试图获取的路由是 localhost/members/group/view-more/page/2 等等,但是如果在分页器中单击 next 等等,它会重定向到 localhost/members (默认布局) .
另外,这是我的控制器的完整代码(根据要求)
class GroupsController extends AbstractActionController
protected $groups_service;
protected $groups_table;
public function indexAction()
return new ViewModel(array('groups' => $this->getGroupsService()->listGroupsIndex()));
public function viewallaction()
return new ViewModel(array('groups' => $this->getGroupsService()->getAllUserGroups()));
public function viewmoreAction()
$paginator = new Paginator(new DbTableGateway($this->getGroupsTable(), array('member_id' => $this->getGroupsService()->grabUserId())));
$page = 1;
if ($this->params()->fromRoute('page'))
$page = $this->params()->fromRoute('page');
$paginator->setCurrentPageNumber((int)$page);
$paginator->setItemCountPerPage(5);
return new ViewModel(array('paginator' => $paginator));
public function getgroupsAction()
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
echo json_encode($this->getGroupsService()->listGroups());
return $view_model;
public function getgroupmembersonlineAction()
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try
echo json_encode($this->getGroupsService()->getGroupMemsOnline());
catch (GroupMembersOnlineException $e)
echo json_encode($e->getMessage());
return $view_model;
public function grouphomeAction()
$id = $this->params()->fromRoute('id', 0);
if (0 === $id)
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
if (!$this->getGroupsService()->getGroupInformation($id))
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
return new ViewModel(array('group_info' => $this->getGroupsService()->getGroupInformation($id)));
public function getonegroupmembersonlineAction()
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
$id = $this->params()->fromRoute('id');
try
echo json_encode($this->getGroupsService()->getGroupMemsOnline($id));
catch (GroupMembersOnlineException $e)
echo json_encode($e->getMessage());
return $view_model;
public function leavegroupAction()
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
$group_id = $this->params()->fromRoute('id');
try
echo json_encode($this->getGroupsService()->leaveTheGroup($group_id));
catch (GroupsException $e)
echo json_encode($e->getMessage());
return $view_model;
public function creategroupAction()
$form = new CreateGroupForm();
return new ViewModel(array(
'form' => $form
));
public function cgroupAction()
$form = new CreateGroupForm();
$request = $this->getRequest();
if ($request->isPost())
$create_group = new CreateGroup();
$form->setInputFilter($create_group->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
$create_group->exchangeArray($form->getData());
try
if ($this->getGroupsService()->createNewGroup($create_group))
$this->flashMessenger()->addSuccessMessage("Group was created successfully!");
return $this->redirect()->toUrl('create-group-success');
catch (GroupsException $e)
$this->flashMessenger()->addErrorMessage((string)$e->getMessage());
return $this->redirect()->toUrl('create-group-failure');
else
$this->flashMessenger()->addErrorMessage("Invalid form. Please correct this and try again.");
return $this->redirect()->toUrl('create-group-failure');
public function postgroupmessageAction()
public function postgroupeventAction()
public function joingroupAction()
$id = $this->params()->fromRoute('id');
$form = new JoinGroupForm();
return new ViewModel(array('form' => $form, 'id' => $id));
public function jgroupAction()
$form = new JoinGroupForm();
$request = $this->getRequest();
if ($request->isPost())
$join_group = new JoinGroup();
$form->setInputFilter($join_group->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
$join_group->exchangeArray($form->getData());
try
if (false !== $this->getGroupsService()->joinTheGroup($_POST['group_id'], $join_group))
$this->flashMessenger()->addSuccessMessage("Request to join group sent.");
return $this->redirect()->toUrl('join-group-success');
catch (GroupsException $e)
$this->flashMessenger()->addErrorMessage((string)$e->getMessage());
return $this->redirect()->toUrl('join-group-failure');
else
$messages = $form->getMessages();
$this->flashMessenger()->addErrorMessage("Invalid form. Please correct this and try again.");
return $this->redirect()->toUrl('join-group-failure');
public function joingroupsuccessAction()
public function joingroupfailureAction()
public function viewgroupsAction()
return new ViewModel(array('groups' => $this->getGroupsService()->listAllGroups()));
public function creategroupsuccessAction()
public function creategroupfailureAction()
public function getGroupsService()
if (!$this->groups_service)
$this->groups_service = $this->getServiceLocator()->get('Members\Model\GroupsModel');
return $this->groups_service;
public function getGroupsTable()
if (!$this->groups_table)
$this->groups_table = new TableGateway('group_members', $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
return $this->groups_table;
【问题讨论】:
我看到你的控制器('viewmore')和module.config('view-more')中有不同的动作名称。你也应该检查你的 paginator.phtml。看手册:framework.zend.com/manual/2.4/en/modules/…. 我无法在控制器的操作中使用 view-more。我试图使用 - 将其分开。 这是在我制作的另一个分页器中工作的,不知道为什么不是这个。 你能告诉我们控制器的完整代码吗? 刚刚添加到帖子中 【参考方案1】:您的配置中似乎有一个 type-o。根据控制器其余部分的逻辑,它可能会决定重定向或转发到另一个操作,从而导致显示不正确的页面(屏幕截图 3)。
您的控制器操作的名称是viewmore
,但在路由配置中您有view-more
。找不到此操作。将操作重命名为 viewMore
或将路由中配置的操作更改为 viewmore
:
解决方案 1:
更改操作的名称。操作的名称将在配置、路由等中为“查看更多”。
public function viewMoreAction()
$paginator = new Paginator(new DbTableGateway($this->getGroupsTable()));
$page = 1;
if ($this->params()->fromRoute('page'))
$page = $this->params()->fromRoute('page');
$paginator->setCurrentPageNumber((int)$page);
$paginator->setItemCountPerPage(5);
return new ViewModel(array('paginator' => $paginator));
解决方案 2:
更改配置中的名称,以便正确匹配操作。
'paginator' => array(
'type' => 'Segment',
'options' => array(
'route' => '/groups/view-more/[page/:page]',
'constraints' => array(
'page' => '[0-9]*',
),
),
'defaults' => array(
'controller' => 'Members\Controller\Groups',
'action' => 'viewmore',
),
),
顺便说一句,为了让您的生活更轻松,您可以开始按类的名称引用类,如下所示:Members\Controller\Groups::class
。请参阅this page 关于 class 关键字。这样,您的编辑器将跟踪类的使用情况。
编辑
您创建的路由称为groups
和paginator
。在您的代码中,您通过members/groups
和members/paginator
调用路由。我认为这是不正确的。
【讨论】:
不幸的是,它仍然在解决我遇到的问题(屏幕截图 3)。不知道为什么了.. 但是您将此标记为已接受?你可以用更多细节开始另一个问题,我相信 *** 可以帮助你。 好的,没问题。您能否向我们提供有关该问题的更多详细信息?你能检测到重定向吗?您期望什么 url,结果是什么 url?您的Module.php
中的代码是什么?
我在module.php中添加了代码和我想要得到的路由,希望够了,如果没有,请告诉我:)
尝试将您视图中的路线从 members/paginator
更改为 paginator
。以上是关于Zend Framework 2 Paginator Route 不起作用的主要内容,如果未能解决你的问题,请参考以下文章
文件上传表单的 Zend 验证器大小 - Zend Framework 2.3
文件上传表单的 Zend 验证器大小 - Zend Framework 2.3
如何模拟 Zend\Form 提交而不在 Zend Framework 2/3 中显示表单?
让 Zend Framework 2 Memcached 工作