/** * Convert a paginator to array * * @param Paginator $paginator * @param string $key root key for items, leave null to return items in root * @return array */ protected function paginatorToArray(Paginator $paginator, $key = null) { $items = iterator_to_array($paginator->getCurrentItems()); if (null === $key) { return $items; } return array('pages' => $paginator->count(), 'current' => $paginator->getCurrentPageNumber(), 'count' => $paginator->getTotalItemCount(), $key => $items); }
public function getPagination($iPageNumber = 0, $iCountPerPage = 0) { $paginatorAdapter = new DbSelect($this->mAdministratorTb->getSql()->select()->columns(array('id', 'role_id', 'username', 'realname', 'raw_add_time')), $this->mAdministratorTb->getAdapter(), $this->mAdministratorTb->getResultSetPrototype()); $paginator = new Paginator($paginatorAdapter); $paginator->setCurrentPageNumber($iPageNumber)->setItemCountPerPage($iCountPerPage); $aRows = $this->mCore->IteratorToArray($paginator->getCurrentItems()); $iTotal = $paginator->getTotalItemCount(); return json_encode(array('rows' => $aRows, 'total' => $iTotal)); }
public function getPagination($iPageNumber = 0, $iCountPerPage = 0, $aOptions = array()) { $paginatorAdapter = new DbSelect($this->mAuthorityTb->getSql()->select()->where($aOptions), $this->mAuthorityTb->getAdapter(), $this->mAuthorityTb->getResultSetPrototype()); $paginator = new Paginator($paginatorAdapter); $paginator->setCurrentPageNumber($iPageNumber)->setItemCountPerPage($iCountPerPage); $iTotal = $paginator->getTotalItemCount(); $aRows = $this->mCore->IteratorToArray($paginator->getCurrentItems()); return json_encode(array('rows' => $aRows, 'total' => $iTotal)); }
public function testWithCacheDisabled() { $this->_paginator->setCacheEnabled(false); $this->_paginator->setCurrentPageNumber(1)->getCurrentItems(); $cachedPageItems = $this->_paginator->getPageItemCache(); $expected = new \ArrayIterator(range(1, 10)); $this->assertEquals(array(), $cachedPageItems); $pageItems = $this->_paginator->getCurrentItems(); $this->assertEquals($expected, $pageItems); }
public function indexAction() { $currentPage = $this->params()->fromRoute('page', null); $adapter = $this->jobTable->getAdapter(); $select = $this->jobTable->getAll(); $paginator = new Paginator(new \Zend\Paginator\Adapter\DbSelect($select, $adapter)); $paginator->setCurrentPageNumber($currentPage); $paginator->setDefaultItemCountPerPage($this->config['admin_element_pagination']); $jobs = $paginator->getCurrentItems(); return new ViewModel(array('jobs' => $jobs, 'paginator' => $paginator)); }
public function getCurrentItems() { /** @var Commit[] $commits */ $commits = parent::getCurrentItems(); foreach ($commits as $commit) { foreach ($this->getCommitFileStatusMapper()->forCommit($commit) as $status) { $commit->addCommitFileStatus($status); } $commit->setRepository($this->getRepositoryMapper()->findById($commit->repository_id)); } return $commits; }
public function indexAction() { $categories = $this->categoryTable->fetchAll(); $results = array(); $adapter = $this->jobTable->getAdapter(); foreach ($categories as $category) { $select = $this->jobTable->getActiveJobsForPagination($category->id_category, $this->config['job_nb_valid_days']); $paginator = new Paginator(new \Zend\Paginator\Adapter\DbSelect($select, $adapter)); $paginator->setCurrentPageNumber(0); $paginator->setDefaultItemCountPerPage($this->config['nb_job_by_category']); $jobs = $paginator->getCurrentItems(); $activeJobs = $paginator->getTotalItemCount(); $results[] = array('category' => $category, 'job' => $jobs, 'activeJobs' => $activeJobs); } $nbJobByCategory = $this->config['nb_job_by_category']; return new ViewModel(array('results' => $results, 'nbJobByCategory' => $nbJobByCategory)); }
public function indexAction() { /** @var QueryBuilder $qb */ $qb = $this->getObjectManager()->createQueryBuilder(); $qb->select('w')->from(Word::class, 'w'); $form = new WordSearchForm(); $form->setData($this->params()->fromQuery()); $form->setInputFilter(new WordSearchInputFilter()); // it doesn't matter if the form is not valid, as we would fill in default values anyway. This is just to avoid the default error messages $form->isValid(); // set query, direction and order for the querybuilder $direction = strtolower($form->getData()['d']); $direction = $direction == 'desc' ? 'desc' : 'asc'; $orderBy = strtolower($form->getData()['o']); switch ($orderBy) { case 'created': $order = 'createdAt'; break; case 'updated': $order = 'updatedAt'; break; default: $orderBy = $order = 'word'; break; } $qb->orderBy('w.' . $order, $direction); // no need to avoid SQL injection, as doctrine does this for us $query = $form->getData()['q']; $qb->where('w.word LIKE :query')->setParameter('query', '%' . $query . '%'); $itemsPerPage = 50; // set up the paginator $adapter = new DoctrineAdapter(new ORMPaginator($qb->getQuery())); $paginator = new Paginator($adapter); $paginator->setDefaultItemCountPerPage(50); $page = (int) $this->params()->fromQuery('p'); if ($page != null) { $paginator->setCurrentPageNumber($page); } else { $paginator->setCurrentPageNumber(1); } $pages = $paginator->getTotalItemCount() / $itemsPerPage; $paginator->setPageRange($pages); $viewModel = new ViewModel(); $viewModel->setVariables(['words' => $paginator->getCurrentItems(), 'pageCount' => $paginator->getPageRange() + 1, 'currentPage' => $paginator->getCurrentPageNumber(), 'orderBy' => $orderBy, 'direction' => $direction, 'query' => $query, 'form' => $form]); return $viewModel; }
public function listAction() { // Get params from matched route $slug = $this->params()->fromRoute('slug', null); $currentPage = $this->params()->fromRoute('page', null); $adapter = $this->jobTable->getAdapter(); if (!is_null($slug)) { $category = $this->categoryTable->getCategoryBySlug($slug); $select = $this->jobTable->getActiveJobsForPagination($category->id_category, $this->config['job_nb_valid_days']); $paginator = new Paginator(new \Zend\Paginator\Adapter\DbSelect($select, $adapter)); $paginator->setCurrentPageNumber($currentPage); $paginator->setDefaultItemCountPerPage($this->config['nb_job_pagination']); $jobs = $paginator->getCurrentItems(); return new ViewModel(array('category' => $category, 'jobs' => $jobs, 'paginator' => $paginator, 'id' => $category->idCategory, 'slug' => $slug)); } else { $this->getResponse()->setStatusCode(404); return; } }
/** * getList * * @return mixed|JsonModel */ public function getList() { //ACCESS CHECK if (!$this->rcmIsAllowed('sites', 'admin')) { $this->getResponse()->setStatusCode(Response::STATUS_CODE_401); return $this->getResponse(); } /** @var \Doctrine\ORM\EntityManagerInterface $entityManager */ $entityManager = $this->getEntityManager(); /** @var \Rcm\Repository\Site $siteRepo */ $siteRepo = $entityManager->getRepository('\\Rcm\\Entity\\Site'); $createQueryBuilder = $siteRepo->createQueryBuilder('site')->select('site')->leftJoin('site.domain', 'domain')->leftJoin('site.country', 'country')->leftJoin('site.language', 'language')->orderBy('domain.domain', 'ASC'); $query = $createQueryBuilder->getQuery(); $searchQuery = $this->params()->fromQuery('q'); if ($searchQuery) { $createQueryBuilder->where($createQueryBuilder->expr()->like('domain.domain', ':searchQuery')); $query = $createQueryBuilder->getQuery(); $query->setParameter('searchQuery', $searchQuery . '%'); } $adaptor = new DoctrinePaginator(new ORMPaginator($query)); $paginator = new Paginator($adaptor); $paginator->setDefaultItemCountPerPage(10); $page = (int) $this->params()->fromQuery('page'); if ($page) { $paginator->setCurrentPageNumber($page); } $pageSize = (int) $this->params()->fromQuery('page_size'); if ($pageSize) { $paginator->setItemCountPerPage($pageSize); } $sitesObjects = $paginator->getCurrentItems(); $sites = []; /** @var \Rcm\Entity\Site $site */ foreach ($sitesObjects as $site) { $sites[] = $site->toArray(); } $list['items'] = $sites; $list['itemCount'] = $paginator->getTotalItemCount(); $list['pageCount'] = $paginator->count(); $list['currentPage'] = $paginator->getCurrentPageNumber(); return new ApiJsonModel($list, 0, 'Success'); }
/** * Get installed modules * * @param integer $page * @param integer $perPage * @param string $orderBy * @param string $orderType * @param array $filters * string status * string type * @return object */ public function getInstalledModules($page = 1, $perPage = 0, $orderBy = null, $orderType = null, array $filters = []) { $orderFields = ['id', 'type', 'status', 'version', 'vendor', 'email']; $orderType = !$orderType || $orderType == 'desc' ? 'desc' : 'asc'; $orderBy = $orderBy && in_array($orderBy, $orderFields) ? $orderBy : 'id'; $select = $this->select(); $select->from(['a' => 'application_module'])->columns(['id', 'name', 'type', 'status', 'version', 'vendor', 'email' => 'vendor_email', 'description'])->join(['b' => 'application_module_depend'], 'a.id = b.depend_module_id', ['module_depends' => 'id'], 'left')->order($orderBy . ' ' . $orderType); // filter by status if (!empty($filters['status'])) { switch ($filters['status']) { case self::MODULE_STATUS_ACTIVE: case self::MODULE_STATUS_NOT_ACTIVE: $select->where(['a.status' => $filters['status']]); break; default: } } // filter by type if (!empty($filters['type'])) { switch ($filters['type']) { case self::MODULE_TYPE_SYSTEM: case self::MODULE_TYPE_CUSTOM: $select->where(['a.type' => $filters['type']]); break; default: } } $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter)); $paginator->setCurrentPageNumber($page); $paginator->setItemCountPerPage(PaginationUtility::processPerPage($perPage)); $paginator->setPageRange(SettingService::getSetting('application_page_range')); // load the custom deactivated module's translations foreach ($paginator->getCurrentItems() as $module) { if ($module['type'] == self::MODULE_TYPE_CUSTOM && $module['status'] == self::MODULE_STATUS_NOT_ACTIVE) { $this->addModuleTranslations($this->getSystemModuleConfig($module['name'], false)); } } return $paginator; }
/** * Return list of resources * * @param callable $queryBuilderCallback * @param callable $queryCallback * @throws \Application\Library\Exception\ValidationException * @return mixed */ public function getList(\Closure $queryBuilderCallback = null, \Closure $queryCallback = null) { $form = new ModelFilterForm(); $form->setData($this->params()->fromQuery()); if (!$form->isValid()) { throw new ValidationException($form->getMessages(), 400); } $limit = $form->getData()['rows']; $page = $form->getData()['page']; $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $queryBuilder->select('c')->from($this->entityClass, 'c'); if (!is_null($queryBuilderCallback)) { $queryBuilderCallback($queryBuilder); } $query = $queryBuilder->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY); if (!is_null($queryCallback)) { $queryCallback($query); } $paginator = new Paginator(new DoctrinePaginator(new ORMPaginator($query))); $paginator->setCurrentPageNumber($page)->setItemCountPerPage($limit); $return = array('page' => $paginator->getCurrentPageNumber(), 'total' => ceil($paginator->getTotalItemCount() / $limit), 'records' => $paginator->getTotalItemCount(), 'rows' => $paginator->getCurrentItems()->getArrayCopy()); return new JsonModel($return); }
public function constructForeignKeys(Paginator $paginator) { if (!$this->allowForeignKeys) { return $paginator; } foreach ($this->foreignKeys as $key) { foreach ($paginator->getCurrentItems() as $item) { if ($this->serviceLocator->has('model\\' . $key->table)) { try { $table = $this->serviceLocator->get('model\\' . $key->table)->getTable(); $table->getSelect()->reset('where'); $object = $table->get($item->{$key->name}, $key->col, true); } catch (Exception $e) { throw new \Exception('Can\'t find col ' . $key->col . ' in model ' . $key->table); } } else { throw new \Exception('Can\'t find \'model\' ' . $key->table . ' service'); } $object = $object ? $object->count() == 1 ? current($object->getArrayCopy()) : $object->getArrayCopy() : null; $item->{$key->key ? $key->key : $key->table} = $object; $functionName = $key->table; $snakeCase = strpos($functionName, '_'); if ($snakeCase) { $functionName = ucwords($functionName, '_'); $functionName = str_replace('_', '', $functionName); } else { $functionName = ucfirst($functionName); } $functionName = 'get' . $functionName; $getFunction = function () use($item, $key) { return $item->{$key->key ? $key->key : $key->table}; }; $item->methods[$functionName] = \Closure::bind($getFunction, $item, get_class($item)); } } return $paginator; }
public function listarOcorrenciaAction() { try { if ($this->getRequest()->isPost()) { $limit = json_decode($this->getRequest()->getPost()['limit'], true); $filters = json_decode($this->getRequest()->getPost()['filters'], true); $filters = $filters['filters']; // $filters = array($filters['filters']); $sortField = $this->getRequest()->getPost()['sortField']; $sortDirection = $this->getRequest()->getPost()['sortDirection']; $page = json_decode($this->getRequest()->getPost()['page'], true); $lotacaoSession = new Container('lotacaoVisibilidade'); $lotacao = $lotacaoSession->lotacaoVisibilidade; $dados = array('id' => $this->getRequest()->getPost()['id'], 'placaVeiculo' => $this->getRequest()->getPost()['placaVeiculo.placa'], 'lotacaoMacro' => $lotacao); $ocorrenciaNegocio = $this->getServiceLocator()->get('Frota\\Negocio\\Ocorrencia'); // if ($filtro) { $retorno = $ocorrenciaNegocio->getRepository()->listarOcorrencia($filters, $dados, $sortField, $sortDirection); // } else { // $retorno = $ocorrenciaNegocio->getRepository()->listarOcorrencia($filtro, $dados, $sortField, $sortDirection); // } $paginator = new Paginator(new ArrayAdapter($retorno)); $paginator->setCurrentPageNumber($page); $paginator->setDefaultItemCountPerPage($limit); $count = $paginator->getItemCount($retorno); $itemsArray = (array) $paginator->getCurrentItems(); return new JsonModel(array("data" => $itemsArray, "message" => "Ocorrência(s) listada(s) com sucesso", "success" => true, "total" => $count)); } } catch (ValidacaoException $exc) { return new JsonModel(array("data" => "", "message" => $exc->getMessage(), "success" => false)); } catch (Exception $exc) { $logger = $this->getServiceLocator()->get('Zend\\Log'); $logger->err($exc, array("Ocorreu um erro:")); return new JsonModel(array("data" => "", "message" => $exc->getMessage(), "success" => false)); } return new JsonModel(array("data" => "", "message" => "Erro na busca dos registros.", "success" => false)); }
/** * @param Paginator $paginator */ public function setPaginator(Paginator $paginator) { foreach ($paginator->getCurrentItems() as $k => $item) { $this->setVariable($k, $this->hydrator->extract($item)); } }
public function testFilter() { $filter = new Filter\Callback(array($this, 'filterCallback')); $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); $paginator->setFilter($filter); $page = $paginator->getCurrentItems(); $this->assertEquals(new \ArrayIterator(range(10, 100, 10)), $page); }
public function listarCnhsVencidasAction() { try { // $scope.cnhsVencidas = [{"matricula": "565", "bairro": "Vincente ires", "cargo": {"codigo": "T", "descricao": "TEMPOR\u00c1RIO"}, "idCargo": "T", "cep": "45454645", "cnh": "123465", "dataValidadeCnh": {"date": "2015-04-20 15:01:30", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "Colonia VP", "municipio": {"id": 2214, "nome": "BONITO ", "uf": {"sigla": "MS", "nome": "MATO GROSSO DO SUL"}}, "uf": {"sigla": "MS", "nome": "MATO GROSSO DO SUL"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Fulano de Tal", "nomeImpresso": "Fulaninho", "telefone": "6181274017", "tipoCategoriaCnh": "E", "isCnhVencida": true}, {"matricula": "sadasd", "bairro": "asdasd", "cargo": {"codigo": "R", "descricao": "REQUISITADO"}, "idCargo": "R", "cep": "71929000", "cnh": "sadasd", "dataValidadeCnh": {"date": "2015-07-27 15:01:44", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "asdasd", "municipio": {"id": 28, "nome": "BARRA DE S\u00c3O MIGUEL ", "uf": {"sigla": "AL", "nome": "ALAGOAS"}}, "uf": {"sigla": "AL", "nome": "ALAGOAS"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Rodrigo", "nomeImpresso": "rodrigo", "telefone": "6181274017", "tipoCategoriaCnh": "B", "isCnhVencida": true}, {"matricula": "1152", "bairro": "SAnta Maria", "cargo": {"codigo": "NTC20600", "descricao": "TECNICO DE APOIO ESPECIALIZADO"}, "idCargo": "NTC20600", "cep": "70000000", "cnh": "123134343", "dataValidadeCnh": {"date": "2015-09-26 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "Rua 45", "municipio": {"id": 127, "nome": "ANAM\u00c3 ", "uf": {"sigla": "AM", "nome": "AMAZONAS"}}, "uf": {"sigla": "AM", "nome": "AMAZONAS"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Joseliton Silva", "nomeImpresso": "Joseliton", "telefone": null, "tipoCategoriaCnh": "B", "isCnhVencida": false}, {"matricula": "1168-1", "bairro": "ARNIQUEIRA", "cargo": {"codigo": "NTC20600", "descricao": "TECNICO DE APOIO ESPECIALIZADO"}, "idCargo": "NTC20600", "cep": "70000000", "cnh": "234234343", "dataValidadeCnh": {"date": "2015-10-15 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "SHIS SUL", "municipio": {"id": 1140, "nome": "ANAJATUBA ", "uf": {"sigla": "MA", "nome": "MARANHAO"}}, "uf": {"sigla": "MA", "nome": "MARANHAO"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "JORGEVAN S. DE PAULA", "nomeImpresso": "JORGEVAN", "telefone": "2343434", "tipoCategoriaCnh": "I", "isCnhVencida": false}]; // $itemsArray = json_decode('[{"matricula": "56w5", "bairro": "Vincente ires", "cargo": {"codigo": "T", "descricao": "TEMPOR\u00c1RIO"}, "idCargo": "T", "cep": "45454645", "cnh": "123465", "dataValidadeCnh": {"date": "2015-04-20 15:01:30", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "Colonia VP", "municipio": {"id": 2214, "nome": "BONITO ", "uf": {"sigla": "MS", "nome": "MATO GROSSO DO SUL"}}, "uf": {"sigla": "MS", "nome": "MATO GROSSO DO SUL"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Fulano de Tal", "nomeImpresso": "Fulaninho", "telefone": "6181274017", "tipoCategoriaCnh": "E", "isCnhVencida": true}, {"matricula": "sadasd", "bairro": "asdasd", "cargo": {"codigo": "R", "descricao": "REQUISITADO"}, "idCargo": "R", "cep": "71929000", "cnh": "sadasd", "dataValidadeCnh": {"date": "2015-07-27 15:01:44", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "asdasd", "municipio": {"id": 28, "nome": "BARRA DE S\u00c3O MIGUEL ", "uf": {"sigla": "AL", "nome": "ALAGOAS"}}, "uf": {"sigla": "AL", "nome": "ALAGOAS"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Rodrigo", "nomeImpresso": "rodrigo", "telefone": "6181274017", "tipoCategoriaCnh": "B", "isCnhVencida": true}, {"matricula": "1152", "bairro": "SAnta Maria", "cargo": {"codigo": "NTC20600", "descricao": "TECNICO DE APOIO ESPECIALIZADO"}, "idCargo": "NTC20600", "cep": "70000000", "cnh": "123134343", "dataValidadeCnh": {"date": "2015-09-26 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "Rua 45", "municipio": {"id": 127, "nome": "ANAM\u00c3 ", "uf": {"sigla": "AM", "nome": "AMAZONAS"}}, "uf": {"sigla": "AM", "nome": "AMAZONAS"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "Joseliton Silva", "nomeImpresso": "Joseliton", "telefone": null, "tipoCategoriaCnh": "B", "isCnhVencida": false}, {"matricula": "1168-1", "bairro": "ARNIQUEIRA", "cargo": {"codigo": "NTC20600", "descricao": "TECNICO DE APOIO ESPECIALIZADO"}, "idCargo": "NTC20600", "cep": "70000000", "cnh": "234234343", "dataValidadeCnh": {"date": "2015-10-15 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "endereco": "SHIS SUL", "municipio": {"id": 1140, "nome": "ANAJATUBA ", "uf": {"sigla": "MA", "nome": "MARANHAO"}}, "uf": {"sigla": "MA", "nome": "MARANHAO"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "nome": "JORGEVAN S. DE PAULA", "nomeImpresso": "JORGEVAN", "telefone": "2343434", "tipoCategoriaCnh": "I", "isCnhVencida": false}]'); // return new JsonModel(array("data" => $itemsArray, "message" => "Cnhs vencidas listado(s) com sucesso", "success" => true, "total" => $count)); // $scope.veiculosParaRevisao = [{"placa": "DDD2341", "anoFabricacao": 2012, "chassi": "1212", "combustivel": {"id": 1, "descricao": "GASOLINA"}, "dataDoacao": {"date": "2015-07-15 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "dataCompra": {"date": "2014-07-17 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "lotacao": {"codigo": 410000000, "codigoPai": 400000000, "codigoMacro": null, "descricao": "PROCURADORIA-GERAL DA JUSTICA MILITAR", "sigla": "PGJM"}, "marcaModelo": {"id": 4, "marca": "FIAT", "modelo": "UNO VIVACE 1.0", "kmRevisao": 10000, "mesesRevisao": 12}, "descricaoMarcaModelo": "FIAT\/UNO VIVACE 1.0", "placaMpm": "asd4323", "hodometro": 9543, "proximaKmRevisao": 5000, "proximaDataRevisao": {"date": "2015-01-17 00:00:00", "timezone_type": 3, "timezone": "America\/Sao_Paulo"}, "revisoesFabrica": {}, "kmRevisao": 5000, "mesesRevisao": 6, "status": "2"}]; if ($this->getRequest()->isPost()) { $limit = json_decode($this->getRequest()->getPost()['limit'], true); $filtro = $this->getRequest()->getPost()['filtro']; $page = json_decode($this->getRequest()->getPost()['page'], true); $lotacaoSession = new Container('lotacaoVisibilidade'); $lotacao = $lotacaoSession->lotacaoVisibilidade; $dados = array('id' => $this->getRequest()->getPost()['id'], 'nome' => $this->getRequest()->getPost()['nome'], 'lotacao' => $lotacao); $motoristaNegocio = $this->getServiceLocator()->get('Frota\\Negocio\\Motorista'); $retorno = $motoristaNegocio->getRepository()->listarCnhsVencidas($filtro, $dados); $paginator = new Paginator(new ArrayAdapter($retorno)); $paginator->setCurrentPageNumber($page); $paginator->setDefaultItemCountPerPage($limit); $count = $paginator->getItemCount($retorno); $itemsArray = (array) $paginator->getCurrentItems(); return new JsonModel(array("data" => $itemsArray, "message" => "Cnhs vencidas listado(s) com sucesso", "success" => true, "total" => $count)); } } catch (ValidacaoException $exc) { return new JsonModel(array("data" => "", "message" => $exc->getMessage(), "success" => false)); } catch (Exception $exc) { $logger = $this->getServiceLocator()->get('Zend\\Log'); $logger->err($exc, array("Ocorreu um erro:")); return new JsonModel(array("data" => "", "message" => $exc->getMessage(), "success" => false)); } return new JsonModel(array("data" => "", "message" => "Erro na busca dos registros.", "success" => false)); }
public function mesIndicsAction() { $this->headTitle("liste de mes indicateurs"); $serviceManager = $this->getServiceLocator(); $config = $serviceManager->get('Configuration'); $currentPage = $this->params()->fromRoute('page', null); $max_per_page = $config['pagination']['per_page_size']; $authService = new AuthenticationService(); if ($authService->hasIdentity()) { // Identity exists; get it $etabId = $authService->getIdentity()->et_code_fk; $puiId = $authService->getIdentity()->pui_code_fk; $userId = $authService->getIdentity()->user_code_pk; } /** @var $entityManager \Doctrine\ORM\EntityManager */ $entityManager = $serviceManager->get('Doctrine\\ORM\\EntityManager'); $indicateurRepository = $entityManager->getRepository('Indicateur\\Entity\\Indicateur'); $offset = ($currentPage - 1) * $max_per_page; if ($currentPage == 1) { $offset = null; } /** @var $indicateurRepository \Indicateur\Entity\Repository\Indicateur */ $indicateurRepository = $entityManager->getRepository('Indicateur\\Entity\\Indicateur'); $results = $indicateurRepository->getPaginatorIndicAttrib($offset, $max_per_page, $userId); $adapter = new PaginatorAdapter($results); $paginator = new Paginator($adapter); $paginator->setCurrentPageNumber($currentPage); $paginator->setItemCountPerPage($max_per_page); $indics = $paginator->getCurrentItems(); return new ViewModel(array("indics" => $indics, "paginator" => $paginator)); }
/** * Load the data */ public function loadData() { if (true === $this->isDataLoaded) { return true; } if ($this->isInit() !== true) { throw new \Exception('The init() method has to be called, before you can call loadData()!'); } if ($this->hasDataSource() === false) { throw new \Exception('No datasource defined! Please call "setDataSource()" first"'); } /** * Apply cache */ $renderer = $this->getRenderer(); /** * Step 1.1) Only select needed columns (performance) */ $this->getDataSource()->setColumns($this->getColumns()); /** * Step 1.2) Sorting */ foreach ($renderer->getSortConditions() as $condition) { $this->getDataSource()->addSortCondition($condition['column'], $condition['sortDirection']); } /** * Step 1.3) Filtering */ foreach ($renderer->getFilters() as $filter) { $this->getDataSource()->addFilter($filter); } $this->getDataSource()->execute(); $paginatorAdapter = $this->getDataSource()->getPaginatorAdapter(); \Zend\Paginator\Paginator::setDefaultScrollingStyle('Sliding'); $this->paginator = new Paginator($paginatorAdapter); $this->paginator->setCurrentPageNumber($renderer->getCurrentPageNumber()); $this->paginator->setItemCountPerPage($renderer->getItemsPerPage($this->getDefaultItemsPerPage())); /* @var $currentItems \ArrayIterator */ $data = $this->paginator->getCurrentItems(); if (!is_array($data)) { if ($data instanceof \Zend\Db\ResultSet\ResultSet) { $data = $data->toArray(); } elseif ($data instanceof ArrayIterator) { $data = $data->getArrayCopy(); } else { if (is_object($data)) { $add = get_class($data); } else { $add = '[no object]'; } throw new \Exception(sprintf('The paginator returned an unknown result: %s (allowed: \\ArrayIterator or a plain php array)', $add)); } } /* * Save cache */ if ($renderer->isExport() === false) { $cacheData = ['sortConditions' => $renderer->getSortConditions(), 'filters' => $renderer->getFilters(), 'currentPage' => $this->getPaginator()->getCurrentPageNumber()]; $success = $this->getCache()->setItem($this->getCacheId(), $cacheData); if ($success !== true) { /** @var \Zend\Cache\Storage\Adapter\FilesystemOptions $options */ $options = $this->getCache()->getOptions(); throw new \Exception(sprintf('Could not save the datagrid cache. Does the directory "%s" exists and is writeable? CacheId: %s', $options->getCacheDir(), $this->getCacheId())); } } /* * Step 3) Format the data - Translate - Replace - Date / time / datetime - Numbers - ... */ $prepareData = new PrepareData($data, $this->getColumns()); $prepareData->setRendererName($this->getRendererName()); if ($this->hasTranslator()) { $prepareData->setTranslator($this->getTranslator()); } $prepareData->prepare(); $this->preparedData = $prepareData->getData(); $this->isDataLoaded = true; }
/** * Returns the inner iterator for the current entry. * @link http://php.net/manual/en/outeriterator.getinneriterator.php * @return \Iterator The inner iterator for the current entry. */ public function getInnerIterator() { return $this->paginator->getCurrentItems(); }
/** * @group ZF-4207 */ public function testAcceptsTraversableInstanceFromAdapter() { $paginator = new Paginator\Paginator(new \ZendTest\Paginator\TestAsset\TestAdapter()); $this->assertInstanceOf('ArrayObject', $paginator->getCurrentItems()); }
protected function serializePaginator(Paginator $paginator) { return ['data' => ArrayUtils::iteratorToArray($paginator->getCurrentItems()), 'pagination' => ['currentPage' => $paginator->getCurrentPageNumber(), 'pagesCount' => $paginator->count()]]; }