Zend Framework 2 分页器路由不起作用

问题描述 投票:0回答:1

我试图让分页器拆分页面上显示的组数,但由于某种原因,当我尝试转到下一组数据或页面时,它默认返回主布局和索引页面。我不知道为什么会这样,因为我以前这样做过并且效果很好。

这是我的代码:

路线:

'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">&lt; 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 &gt;</a> |
    <?php else: ?>
        <span class="w3-button w3-disabled">Next &gt;</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);
                }
            ),
        );
    }
}

我提供了三个屏幕截图(第一个关于分页器如何显示,第二个关于它如何重定向到错误页面)

https://i.sstatic.net/9KePd.jpg - 第一

https://i.sstatic.net/Q8N16.jpg - 第二个

https://i.sstatic.net/IvWkf.jpg - 第三

我希望这是足够的信息,如果没有,请告诉我,我会尽力添加更多。

谢谢!

更新 -

我试图获取的路线是 localhost/members/group/view-more/page/2 等等,但如果在分页器中单击“下一步”等,它会重定向到 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;
    }
php zend-framework pagination
1个回答
7
投票

您的配置中似乎有一个 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
。有关 class 关键字,请参阅此页。这样您的编辑器将跟踪类的用法。

编辑

您创建的路线称为

groups
paginator
。在您的代码中,您通过
members/groups
members/paginator
调用路线。我认为这是不正确的。

© www.soinside.com 2019 - 2024. All rights reserved.