Я пытаюсь разделить пагинатор на количество групп, отображаемых на странице, но по какой-то причине, когда я пытаюсь перейти к следующему набору данных или странице, он по умолчанию возвращается к основному макету и индексной странице. . Я не уверен, почему это так, потому что я делал это раньше, и все работало нормально.
Вот мой код:
Маршрут:
'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));
}
вид:
No more groups found
Group Id
Group Name
[url=">
[/url]
и вид на страницы (не уверен, нужно ли мне это включать, но подумал, что стоит это сделать)
- of
[url=" class="w3-button">First[/url] |
First |
[url=" class="w3-button">< Previous[/url] |
Previous |
[url=" class="w3-button">Next >[/url] |
Next > |
[url=" class="w3-button">Last[/url]
Last
Код 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);
}
),
);
}
}
Я включил три снимка экрана (1 о том, как отображается пагинатор, а второй о том, как он перенаправляется на неправильную страницу)
https://i.sstatic.net/9KePd.jpg — 1-е место
https://i.sstatic.net/Q8N16.jpg — 2-е место
https://i.sstatic.net/IvWkf.jpg - 3-е место
Надеюсь, это достаточно информации, если нет, дайте мне знать, и я постараюсь добавить больше.
Спасибо!
Обновление -
Я пытаюсь получить маршрут: 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;
}
Подробнее здесь: https://stackoverflow.com/questions/435 ... ot-working
Zend Framework 2 Paginator Route не работает ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1729481861
Anonymous
Я пытаюсь разделить пагинатор на количество групп, отображаемых на странице, но по какой-то причине, когда я пытаюсь перейти к следующему набору данных или странице, он по умолчанию возвращается к основному макету и индексной странице. . Я не уверен, почему это так, потому что я делал это раньше, и все работало нормально.
Вот мой код:
Маршрут:
'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));
}
вид:
No more groups found
Group Id
Group Name
[url=">
[/url]
и вид на страницы (не уверен, нужно ли мне это включать, но подумал, что стоит это сделать)
- of
[url=" class="w3-button">First[/url] |
First |
[url=" class="w3-button">< Previous[/url] |
Previous |
[url=" class="w3-button">Next >[/url] |
Next > |
[url=" class="w3-button">Last[/url]
Last
Код 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);
}
),
);
}
}
Я включил три снимка экрана (1 о том, как отображается пагинатор, а второй о том, как он перенаправляется на неправильную страницу)
https://i.sstatic.net/9KePd.jpg — 1-е место
https://i.sstatic.net/Q8N16.jpg — 2-е место
https://i.sstatic.net/IvWkf.jpg - 3-е место
Надеюсь, это достаточно информации, если нет, дайте мне знать, и я постараюсь добавить больше.
Спасибо!
Обновление -
Я пытаюсь получить маршрут: 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;
}
Подробнее здесь: [url]https://stackoverflow.com/questions/43577050/zend-framework-2-paginator-route-not-working[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия