public function indexAction(Request $request, $page = 1) { $getTypes = $request->query->get('type_filters'); $getSubjects = $request->query->get('subject_filters'); $getPublishers = $request->query->get('publisher_filters'); $typeFilters = !empty($getTypes) ? explode(',', $getTypes) : []; $subjectFilters = !empty($getSubjects) ? explode(',', $getSubjects) : []; $publisherFilters = !empty($getPublishers) ? explode(',', $getPublishers) : []; $journalSearcher = $this->get('fos_elastica.index.search.journal'); $boolQuery = new Query\Bool(); $match = new Query\Match(); $match->setField('status', 1); $boolQuery->addMust($match); $match = new Query\Match(); $match->setField('published', true); $boolQuery->addMust($match); if (!empty($typeFilters) || !empty($subjectFilters) || !empty($publisherFilters)) { foreach ($typeFilters as $type) { $match = new Query\Match(); $match->setField('publisher.publisher_type.name', $type); $boolQuery->addMust($match); } foreach ($subjectFilters as $subject) { $match = new Query\Match(); $match->setField('subjects.subject', $subject); $boolQuery->addMust($match); } foreach ($publisherFilters as $publisher) { $match = new Query\Match(); $match->setField('publisher.name', $publisher); $boolQuery->addMust($match); } } $journalQuery = new Query($boolQuery); $typeAgg = new Aggregation\Terms('types'); $typeAgg->setField('publisher.publisher_type.name'); $typeAgg->setOrder('_term', 'asc'); $typeAgg->setSize(0); $journalQuery->addAggregation($typeAgg); $subjectAgg = new Aggregation\Terms('subjects'); $subjectAgg->setField('subjects.subject'); $subjectAgg->setOrder('_term', 'asc'); $subjectAgg->setSize(0); $journalQuery->addAggregation($subjectAgg); $publisherAgg = new Aggregation\Terms('publishers'); $publisherAgg->setField('publisher.name'); $publisherAgg->setOrder('_term', 'asc'); $publisherAgg->setSize(0); $journalQuery->addAggregation($publisherAgg); $adapter = new ElasticaAdapter($journalSearcher, $journalQuery); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(21); $pagerfanta->setCurrentPage($page); $journals = $pagerfanta->getCurrentPageResults(); $types = $adapter->getResultSet()->getAggregation('types')['buckets']; $subjects = $adapter->getResultSet()->getAggregation('subjects')['buckets']; $publishers = $adapter->getResultSet()->getAggregation('publishers')['buckets']; $data = ['types' => $types, 'subjects' => $subjects, 'publishers' => $publishers, 'type_filters' => $typeFilters, 'subject_filters' => $subjectFilters, 'publisher_filters' => $publisherFilters, 'journals' => $journals, 'pagerfanta' => $pagerfanta, 'page' => 'explore']; return $this->render('OjsSiteBundle:Explore:index.html.twig', $data); }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var SolrIndexer $indexer */ $indexer = $this->getContainer()->get('knp_bundles.indexer.solr'); /** @var EntityManager $em */ $em = $this->getContainer()->get('doctrine')->getManager(); /** @var \Solarium_Client $solarium */ $solarium = $this->getContainer()->get('solarium.client'); /** @var EntityRepository $repository */ $repository = $em->getRepository('KnpBundlesBundle:Bundle'); $query = $solarium->createSelect(); $query->setFields(array('name', 'ownerName')); try { $hasMoreResults = true; $page = 1; while ($hasMoreResults) { $paginator = new Pagerfanta(new SolariumAdapter($solarium, $query)); $paginator->setMaxPerPage(50)->setCurrentPage($page, false, true); foreach ($paginator as $bundle) { $entity = $repository->findOneBy(array('name' => $bundle['name'])); if (!$entity) { $entity = new Bundle(); $entity->setName($bundle['name']); $entity->setOwnerName($bundle['ownerName']); $indexer->deleteBundlesIndexes($entity); $output->writeln(sprintf('The bundle "%s" was deleted from solr index.', $entity->getFullName())); } } $hasMoreResults = $paginator->getNbResults() == 50; $page++; } } catch (\Solarium_Client_HttpException $e) { throw new \Exception('Seems that our search engine is currently offline. Please check later.'); } }
/** * Creates a Doctrine ORM paginator for the given query builder. * * @param DoctrineQuery|DoctrineQueryBuilder $queryBuilder * @param int $page * @param int $maxPerPage * * @return Pagerfanta */ public function createOrmPaginator($queryBuilder, $page = 1, $maxPerPage = self::MAX_ITEMS) { $paginator = new Pagerfanta(new DoctrineORMAdapter($queryBuilder, true, false)); $paginator->setMaxPerPage($maxPerPage); $paginator->setCurrentPage($page); return $paginator; }
/** * @Route("/opencast/mediapackage", name="pumukitopencast") * @Template() */ public function indexAction(Request $request) { if (!$this->has('pumukit_opencast.client')) { throw $this->createNotFoundException('PumukitOpencastBundle not configured.'); } $opencastClient = $this->get('pumukit_opencast.client'); $repository_multimediaobjects = $this->get('doctrine_mongodb')->getRepository('PumukitSchemaBundle:MultimediaObject'); $limit = 10; $page = $request->get("page", 1); $criteria = $this->getCriteria($request); try { list($total, $mediaPackages) = $opencastClient->getMediaPackages(isset($criteria["name"]) ? $criteria["name"]->regex : "", $limit, ($page - 1) * $limit); } catch (\Exception $e) { return new Response($this->render('PumukitOpencastBundle:MediaPackage:error.html.twig', array('message' => $e->getMessage())), 400); } $currentPageOpencastIds = array(); foreach ($mediaPackages as $mediaPackage) { $currentPageOpencastIds[] = $mediaPackage["id"]; } $adapter = new FixedAdapter($total, $mediaPackages); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($limit); $pagerfanta->setCurrentPage($page); $repo = $repository_multimediaobjects->createQueryBuilder()->field("properties.opencast")->exists(true)->field("properties.opencast")->in($currentPageOpencastIds)->getQuery()->execute(); return array('mediaPackages' => $pagerfanta, 'multimediaObjects' => $repo, 'player' => $opencastClient->getPlayerUrl()); }
public function indexAction(Request $req) { $rawSpeakers = $this->app['spot']->mapper(\OpenCFP\Domain\Entity\User::class)->all()->order(['first_name' => 'ASC'])->toArray(); $airports = $this->service(AirportInformationDatabase::class); $rawSpeakers = array_map(function ($speaker) use($airports) { try { $airport = $airports->withCode($speaker['airport']); $speaker['airport'] = ['code' => $airport->code, 'name' => $airport->name, 'country' => $airport->country]; } catch (\Exception $e) { $speaker['airport'] = ['code' => null, 'name' => null, 'country' => null]; } return $speaker; }, $rawSpeakers); // Set up our page stuff $adapter = new ArrayAdapter($rawSpeakers); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(20); $pagerfanta->getNbResults(); if ($req->get('page') !== null) { $pagerfanta->setCurrentPage($req->get('page')); } // Create our default view for the navigation options $routeGenerator = function ($page) { return '/admin/speakers?page=' . $page; }; $view = new TwitterBootstrap3View(); $pagination = $view->render($pagerfanta, $routeGenerator, ['proximity' => 3]); $templateData = ['airport' => $this->app->config('application.airport'), 'arrival' => date('Y-m-d', $this->app->config('application.arrival')), 'departure' => date('Y-m-d', $this->app->config('application.departure')), 'pagination' => $pagination, 'speakers' => $pagerfanta, 'page' => $pagerfanta->getCurrentPage()]; return $this->render('admin/speaker/index.twig', $templateData); }
/** * Renders the tag. * * @param \Netgen\TagsBundle\API\Repository\Values\Tags\Tag $tag * @param \Symfony\Component\HttpFoundation\Request $request * * @return \Symfony\Component\HttpFoundation\Response */ protected function renderTag(Tag $tag, Request $request) { $configResolver = $this->getConfigResolver(); if ($this->adapter instanceof TagAdapterInterface) { $this->adapter->setTag($tag); } $pager = new Pagerfanta($this->adapter); $pager->setMaxPerPage($configResolver->getParameter('tag_view.related_content_list.limit', 'eztags')); $pager->setCurrentPage($request->get('page', 1)); $response = new Response(); $response->headers->set('X-Tag-Id', $tag->id); if ($configResolver->getParameter('tag_view.cache', 'eztags') === true) { $response->setPublic(); if ($configResolver->getParameter('tag_view.ttl_cache', 'eztags') === true) { $response->setSharedMaxAge($configResolver->getParameter('tag_view.default_ttl', 'eztags')); } // Make the response vary against X-User-Hash header ensures that an HTTP // reverse proxy caches the different possible variations of the // response as it can depend on user role for instance. if ($request->headers->has('X-User-Hash')) { $response->setVary('X-User-Hash'); } $response->setLastModified($tag->modificationDate); } return $this->render($configResolver->getParameter('tag_view.template', 'eztags'), array('tag' => $tag, 'pager' => $pager), $response); }
/** * Construct a pagerfanta representation from the current request * * @param AdapterInterface $adapter - The adapter to use * @return QueryablePaginatedRepresentation */ protected function getPagerfantaRepresentation(Request $request, AdapterInterface $adapter) { $pagerfanta = new Pagerfanta($adapter); $limit = $request->query->get('limit'); $zeroLimit = false; if (!$limit && ($limit === 0 || $limit === '0')) { $limit = $pagerfanta->count(); $zeroLimit = true; } if (!$limit) { $limit = 10; } $pagerfanta->setMaxPerPage($limit); $page = $request->query->get('page'); $nbPages = $pagerfanta->getNbPages(); if (!$page) { $page = 1; } // Avoid errors: redirect to max page if ($page > $nbPages) { $page = $nbPages; } $pagerfanta->setCurrentPage($page); $route = new Route($request->get('_route'), $request->attributes->get('_route_params'), false); return new QueryablePaginatedRepresentation(new CollectionRepresentation($pagerfanta->getCurrentPageResults()), $route->getName(), $route->getParameters(), $pagerfanta->getCurrentPage(), $zeroLimit ? 0 : $pagerfanta->getMaxPerPage(), $nbPages, $pagerfanta->count(), null, null, $route->isAbsolute(), $request->query->get('where'), $request->query->get('search'), $request->query->get('order'), null, null, null); }
/** * @param int $page * * @return Pagerfanta */ public function findLatest($page = 1) { $paginator = new Pagerfanta(new DoctrineORMAdapter($this->queryLatest(), false)); $paginator->setMaxPerPage(Post::NUM_ITEMS); $paginator->setCurrentPage($page); return $paginator; }
private function createPager($objects, $page, $limit = 5) { $adapter = new DoctrineODMMongoDBAdapter($objects); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($limit)->setNormalizeOutOfRangePages(true)->setCurrentPage($page); return $pagerfanta; }
/** * Perform a search and return a JSON response. * * @param Request $request * * @return JsonResponse */ public function searchAction(Request $request) { $queryString = $request->query->get('q'); $category = $request->query->get('category', null); $locale = $request->query->get('locale', null); $page = $this->listRestHelper->getPage(); $limit = $this->listRestHelper->getLimit(); $aggregateHits = []; $startTime = microtime(true); $categories = $category ? [$category] : $this->searchManager->getCategoryNames(); foreach ($categories as $category) { $query = $this->searchManager->createSearch($queryString); if ($locale) { $query->locale($locale); } if ($category) { $query->category($category); } foreach ($query->execute() as $hit) { $aggregateHits[] = $hit; } } $time = microtime(true) - $startTime; $adapter = new ArrayAdapter($aggregateHits); $pager = new Pagerfanta($adapter); $pager->setMaxPerPage($limit); $pager->setCurrentPage($page); $representation = new SearchResultRepresentation(new CollectionRepresentation($pager->getCurrentPageResults(), 'result'), 'sulu_search_search', ['locale' => $locale, 'query' => $query, 'category' => $category], (int) $page, (int) $limit, $pager->getNbPages(), 'page', 'limit', false, count($aggregateHits), $this->getCategoryTotals($aggregateHits), number_format($time, 8)); $view = View::create($representation); $context = SerializationContext::create(); $context->enableMaxDepthChecks(); $context->setSerializeNull(true); $view->setSerializationContext($context); return $this->viewHandler->handle($view); }
/** * @param int $page * @return \Symfony\Component\HttpFoundation\Response */ public function listAction($page) { $pagerfanta = new Pagerfanta($this->galleryManager->createPagerfantaAdapter()); $pagerfanta->setMaxPerPage($this->galleriesPerPage); $pagerfanta->setCurrentPage($page); return $this->templating->renderResponse('FSiGalleryBundle:Gallery:list.html.twig', array('galleries' => $pagerfanta, 'preview_photos_count' => $this->previewPhotosCount)); }
/** * @return string */ public function renderPagination(Page $page, Twig_Environment $environment) { $pagerfanta = new Pagerfanta(new PorpaginasAdapter($page)); $pagerfanta->setCurrentPage($page->getCurrentPage()); $pagerfanta->setMaxPerPage($page->getCurrentLimit()); return $environment->getExtension('pagerfanta')->renderPagerfanta($pagerfanta, $this->viewName, $this->options); }
public function indexAction(Request $request, $page) { $querystring = $request->query->get('query'); $finder = $this->get('fos_elastica.finder.videocollection'); $language = $this->get('bestophe_video_collection.movieManager')->getLanguage(); $query = $this->getElasticaResults($querystring, $language); $results = $finder->find($query); $totalHits = count($results); $adapter = new ArrayAdapter($results); $pager = new Pagerfanta($adapter); $maxPerPage = $this->getPagerFantaMaxPerPage(); $pager->setMaxPerPage($maxPerPage); $pager->setCurrentPage($page); // if ($querystring != null && $querystring != '') { // $query = new \Elastica\Query\Match(); // $query->setFieldQuery('title_fr', $querystring); // // $query->setFieldFuzziness('title_fr', 0.7); // // $query->setFieldMinimumShouldMatch('title_fr', '80%'); // // // } else { // $query = new \Elastica\Query\MatchAll(); // } // // $results = $finder->find($query); // // $totalHits = count($results); return $this->render('bestopheVideoCollectionBundle:MovieSection:SearchView.html.twig', array('listMovies' => $pager->getCurrentPageResults(), 'pager' => $pager, 'query' => $querystring, 'totalHits' => $totalHits)); }
/** * Displays the list of blog_post * Note: This is a fully customized controller action, it will generate the response and call * the view. Since it is not calling the ViewControler we don't need to match a specific * method signature. * * @param \eZ\Publish\API\Repository\Values\Content\Location $location containing blog posts * @return \Symfony\Component\HttpFoundation\Response */ public function listBlogPostsAction(Location $location, Request $request) { $response = new Response(); // Setting default cache configuration (you can override it in you siteaccess config) $response->setSharedMaxAge($this->getConfigResolver()->getParameter('content.default_ttl')); // Make the response location cache aware for the reverse proxy $response->headers->set('X-Location-Id', $location->id); $response->setVary('X-User-Hash'); $viewParameters = $request->attributes->get('viewParameters'); // Getting location and content from ezpublish dedicated services $repository = $this->getRepository(); if ($location->invisible) { throw new NotFoundHttpException("Location #{$location->id} cannot be displayed as it is flagged as invisible."); } $content = $repository->getContentService()->loadContentByContentInfo($location->getContentInfo()); // Getting language for the current siteaccess $languages = $this->getConfigResolver()->getParameter('languages'); // Using the criteria helper (a demobundle custom service) to generate our query's criteria. // This is a good practice in order to have less code in your controller. $criteria = $this->get('ezdemo.criteria_helper')->generateListBlogPostCriterion($location, $viewParameters, $languages); // Generating query $query = new Query(); $query->query = $criteria; $query->sortClauses = array(new SortClause\Field('blog_post', 'publication_date', Query::SORT_DESC, $languages[0])); // Initialize pagination. $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->container->getParameter('ezdemo.blog.blog_post_list.limit')); $pager->setCurrentPage($request->get('page', 1)); return $this->render('eZDemoBundle:full:blog.html.twig', array('location' => $location, 'content' => $content, 'pagerBlog' => $pager), $response); }
/** * @QueryParam(name="page", requirements="\d+", default="1", description="Page of the overview") * @QueryParam(name="limit", requirements="\d+", default="10", description="Size of the page") * @QueryParam(name="sort", requirements="[a-z]+", description="Sort parameter") * @QueryParam(name="sort_order", requirements="(asc|desc)", allowBlank=false, default="asc", description="Sort direction") * @QueryParam(name="search", requirements="[a-zA-Z0-9]+", description="Search") * @QueryParam(name="status", requirements="(pending|publish|draft|auto-draft|future|private|inherit|trash)", default="", nullable=true, description="Status of the posts") * @QueryParam(name="by_author", requirements="[a-zA-Z]+", description="By author's username", incompatibles={"search"}) * @QueryParam(name="by_category", requirements="[a-zA-Z]+", description="By category", incompatibles={"search"}) * @QueryParam(name="by_keywords", requirements="[a-zA-Z]+", description="By keywords", incompatibles={"search"}) * @QueryParam(name="format", requirements="[a-z]+", default="lite", description="Format of request") * @Rest\View() */ public function getPostsAction(ParamFetcher $paramFetcher) { $page = $paramFetcher->get("page"); $limit = $paramFetcher->get("limit"); $sort = $paramFetcher->get("sort"); $sort_order = $paramFetcher->get("sort_order"); $search = $paramFetcher->get("search"); $status = $paramFetcher->get("status"); $by_author = $paramFetcher->get("by_author"); $by_category = $paramFetcher->get("by_category"); $by_keywords = $paramFetcher->get("by_keywords"); $format = $paramFetcher->get("format"); $repo = $this->getDoctrine()->getManager()->getRepository('ESGISGabonPostBundle:CorporatePost'); $posts = $repo->getPosts($format); $adapter = new ArrayAdapter($posts); $pager = new Pagerfanta($adapter); $pager->setMaxPerPage($limit); try { $pager->setCurrentPage($page); } catch (NotValidCurrentPageException $e) { throw new NotFoundHttpException(); } $pagerfantaFactory = new PagerfantaFactory(); $paginatedCollection = $pagerfantaFactory->createRepresentation($pager, new Route('api_get_posts', array('page' => $page, 'limit' => $limit, 'sort' => $sort, 'sort_order' => $sort_order)), new CollectionRepresentation($pager->getCurrentPageResults(), 'posts', 'posts')); return $paginatedCollection; }
/** * Lists all ArchivedClock entities within the requested week * * @param integer $year Year in YYYY format * @param integer $month Month in MM format * @param integer $day Day in DD format * * @return Symfony\Component\HttpFoundation\Response */ public function viewAction($year, $month, $day) { if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { throw new AccessDeniedException(); } $em = $this->getDoctrine()->getManager(); $week = new \DateTime(); $week->setDate($year, $month, $day); $week->setTime(0, 0, 0); // Midnight $week = $this->container->get('dt_utils')->getFirstDayOfWeek($week); $archivedClocksQB = $em->createQueryBuilder()->select('ac')->from('OpenSkedgeBundle:ArchivedClock', 'ac')->where('ac.week = :week')->setParameter('week', $week); $page = $this->container->get('request')->query->get('page', 1); $limit = $this->container->get('request')->query->get('limit', 15); $adapter = new DoctrineORMAdapter($archivedClocksQB); $paginator = new Pagerfanta($adapter); try { $paginator->setMaxPerPage($limit); $paginator->setCurrentPage($page); $entities = $paginator->getCurrentPageResults(); } catch (NotValidMaxPerPageException $e) { throw new HttpException(400, 'Not a valid limit', $e, array(), $e->getCode()); } catch (NotValidCurrentPageException $e) { throw $this->createNotFoundException('Page does not exist.'); } return $this->render('OpenSkedgeBundle:HoursReport:view.html.twig', array('week' => $week, 'entities' => $entities, 'paginator' => $paginator)); }
/** * @param LocationQuery $query * @param SearchService $searchService * @param ContentDecoratorFactory $contentDecoratorFactory * @param $maxPerPage * @param int $currentPage * @return Pagerfanta */ public static function buildPager(LocationQuery $query, SearchService $searchService, ContentDecoratorFactory $contentDecoratorFactory, $maxPerPage, $currentPage = 1) { $pager = new Pagerfanta(new static($query, $searchService, $contentDecoratorFactory)); $pager->setMaxPerPage($maxPerPage); $pager->setCurrentPage($currentPage); return $pager; }
public function listReviewsAction($locationId, $viewType, Request $request, $layout = false, array $params = []) { $pager = new Pagerfanta(new LocationSearchAdapter($this->get('metalfrance.repository.review')->getReviewListQuery($locationId, $request->query->get('type') === 'decouvertes'), $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->getConfigResolver()->getParameter('review.list_limit', 'metalfrance')); $pager->setCurrentPage($request->query->get('page', 1)); return $this->get('ez_content')->viewLocation($locationId, $viewType, $layout, ['reviews' => $pager] + $params); }
/** * Displays the list of article. * * @param \Symfony\Component\HttpFoundation\Request $request request object * @param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view * * @return \Symfony\Component\HttpFoundation\Response $location is flagged as invisible */ public function showFolderListAction(Request $request, ContentView $view) { $languages = $this->getConfigResolver()->getParameter('languages'); // Using the criteria helper (a demobundle custom service) to generate our query's criteria. // This is a good practice in order to have less code in your controller. $criteria = $this->get('ezdemo.criteria_helper')->generateListFolderCriterion($view->getLocation(), $this->container->getParameter('ezdemo.folder.folder_view.excluded_content_types'), $languages); // Generating query $query = new LocationQuery(); $query->query = $criteria; $query->sortClauses = array(new SortClause\DatePublished()); // Initialize pagination. $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->container->getParameter('ezdemo.folder.folder_list.limit')); $pager->setCurrentPage($request->get('page', 1)); $includedContentTypeIdentifiers = $this->container->getParameter('ezdemo.folder.folder_tree.included_content_types'); // Get sub folder structure $subContentCriteria = $this->get('ezdemo.criteria_helper')->generateSubContentCriterion($view->getLocation(), $includedContentTypeIdentifiers, $languages); $subContentQuery = new LocationQuery(); $subContentQuery->query = $subContentCriteria; $subContentQuery->sortClauses = array(new SortClause\ContentName()); $searchService = $this->getRepository()->getSearchService(); $subContent = $searchService->findLocations($subContentQuery); $treeItems = array(); foreach ($subContent->searchHits as $hit) { $treeItems[] = $hit->valueObject; } $view->addParameters(['pagerFolder' => $pager, 'treeItems' => $treeItems]); return $view; }
/** * {@inheritdoc} */ public function getData(Parameters $parameters) { // Use output walkers option in DoctrineORMAdapter should be false as it affects performance greatly (see #3775) $paginator = new Pagerfanta(new DoctrineORMAdapter($this->queryBuilder, true, false)); $paginator->setCurrentPage($parameters->get('page', 1)); return $paginator; }
public function createCollection(QueryBuilder $qb, Request $request, $route, array $routeParams = array()) { $page = $request->query->get(self::PARAMETER_NAME_PAGE_NUMBER, 1); $count = $request->query->get(self::PARAMETER_NAME_PAGE_SIZE, self::PAGE_DEFAULT_COUNT); if ($count > self::MAX_PAGE_COUNT) { $count = self::MAX_PAGE_COUNT; } if ($count <= 0) { $count = self::PAGE_DEFAULT_COUNT; } $adapter = new DoctrineORMAdapter($qb); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($count); $pagerfanta->setCurrentPage($page); $players = []; foreach ($pagerfanta->getCurrentPageResults() as $result) { $players[] = $result; } $paginatedCollection = new PaginatedCollection($players, $pagerfanta->getNbResults()); // make sure query parameters are included in pagination links $routeParams = array_merge($routeParams, $request->query->all()); $createLinkUrl = function ($targetPage) use($route, $routeParams) { return $this->router->generate($route, array_merge($routeParams, array(self::PARAMETER_NAME_PAGE_NUMBER => $targetPage))); }; $paginatedCollection->addLink('self', $createLinkUrl($page)); $paginatedCollection->addLink('first', $createLinkUrl(1)); $paginatedCollection->addLink('last', $createLinkUrl($pagerfanta->getNbPages())); if ($pagerfanta->hasNextPage()) { $paginatedCollection->addLink('next', $createLinkUrl($pagerfanta->getNextPage())); } if ($pagerfanta->hasPreviousPage()) { $paginatedCollection->addLink('prev', $createLinkUrl($pagerfanta->getPreviousPage())); } return $paginatedCollection; }
/** * Initializes the pager for a query. * * @param \Doctrine\ORM\QueryBuilder $query Query for packages * @param int $page Pagenumber to retrieve. * @return \Pagerfanta\Pagerfanta */ protected function setupPager($query, $page) { $paginator = new Pagerfanta(new DoctrineORMAdapter($query, true)); $paginator->setMaxPerPage(15); $paginator->setCurrentPage($page, false, true); return $paginator; }
public function createResponseArray($data, $entity, Request $request) { $this->request = $request; $fractal = new Manager(); $fractal->parseIncludes($request->query->get('include', [])); $fractal->setSerializer(new ArraySerializer()); $transformer = $this->transformerFactory->get($entity); if ($data instanceof Pagerfanta) { $pager = $data; $pager->setMaxPerPage($request->query->get('limit', 10)); $pager->setCurrentPage($request->query->get('page', 1)); $results = $pager->getCurrentPageResults(); $resource = new Collection($results, $transformer); $resource->setPaginator(new PagerfantaPaginatorAdapter($pager, [$this, 'paginationRouter'])); } elseif ($data instanceof DoctrineQuery) { $ormAdapter = new DoctrineORMAdapter($data); $pager = new Pagerfanta($ormAdapter); $pager->setMaxPerPage($request->query->get('limit', 10)); $pager->setCurrentPage($request->query->get('page', 1)); $results = $pager->getCurrentPageResults(); $resource = new Collection($results, $transformer); $resource->setPaginator(new PagerfantaPaginatorAdapter($pager, [$this, 'paginationRouter'])); } elseif (is_array($data)) { $resource = new Collection($data, $transformer); } else { $resource = new Item($data, $transformer); } $data = $fractal->createData($resource)->toArray(); return $data; }
/** * @param TaxonInterface $taxon * @param Pagerfanta $results * @param $template * @param $page * @param null $facets * @param null $facetTags * @param null $filters * @param null $searchTerm * @param null $searchParam * @param null $requestMethod * @return \Symfony\Component\HttpFoundation\Response */ private function renderResults(TaxonInterface $taxon, Pagerfanta $results, $template, $page, $facets = null, $facetTags = null, $filters = null, $searchTerm = null, $searchParam = null, $requestMethod = null) { $results->setCurrentPage($page, true, true); $results->setMaxPerPage($this->config->getPaginationMaxPerPage()); $view = $this->view()->setTemplate($this->config->getTemplate($template))->setData(array('taxon' => $taxon, 'products' => $results, 'facets' => $facets, 'facetTags' => $facetTags, 'filters' => $filters, 'searchTerm' => $searchTerm, 'searchParam' => $searchParam, 'requestMethod' => $requestMethod)); return $this->handleView($view); }
/** * Build a Pagerfanta object based on the pagination information. * * The pagination information can be passed as a parameter, and if not the method use the injected provider to * extract pagination information based on the current context. * * @param \Pagerfanta\Adapter\AdapterInterface $adapter Wrapped query * @param PaginatedCollectionRequestInterface $paginationInfo Requested pagination * * @return \PagerFanta\PagerFanta * * @throws \LogicException If no pagination could be used in order to paginate the results * @throws \AlphaLabs\Pagination\Exception\InvalidRequestedPage If the requested pagination could not be applied */ public function paginate(AdapterInterface $adapter, PaginatedCollectionRequestInterface $paginationInfo = null) { if (is_null($paginationInfo)) { if (is_null($this->paginationInfoProvider)) { throw new \LogicException('A PaginatedCollectionRequestProviderInterface must be injected if you want to use pagination ' . 'and don\\t want to handle the pagination info with your own logic.'); } $paginationInfo = $this->paginationInfoProvider->getPaginatedCollectionRequest(); if (is_null($paginationInfo)) { throw new \LogicException('No pagination could be provided by the PaginatedCollectionRequestProviderInterface. The provider ' . 'must at least provide default pagination information in order to use the paginate() method.'); } } $pager = new Pagerfanta($adapter); try { $pager->setMaxPerPage($paginationInfo->getItemsPerPage())->setCurrentPage($paginationInfo->getPage()); } catch (LessThan1CurrentPageException $e) { $invalidPageException = new InvalidRequestedPage(); $invalidPageException->setRequestedPage($paginationInfo->getPage())->setTargetPage(1); throw $invalidPageException; } catch (OutOfRangeCurrentPageException $e) { $invalidPageException = new InvalidRequestedPage(); $invalidPageException->setRequestedPage($paginationInfo->getPage())->setTargetPage($pager->getNbPages() - 1); throw $invalidPageException; } return $pager; }
/** * Get search results from Google. * * {@inheritdoc} */ public function getPagerfanta($query, $locale) { $adapter = new GoogleRestAdapter($this->googleApiKey, $this->getSearchKey($locale), $this->googleSearchAPIUrl, $query, $this->restrictLanguage ? $locale : false, $this->restrictToSite); $pager = new Pagerfanta($adapter); $pager->setMaxPerPage($this->maxPerPage); return $pager; }
public function indexAction($actif, $page, $maxPerPage) { $em = $this->getDoctrine()->getManager(); $layout = $this->getLayout($em); // $maxPerPage = 1; // suppression des offres datant de plus d'un an $dateOld = new \Datetime(); date_sub($dateOld, date_interval_create_from_date_string('1 year')); $query = $this->getDoctrine()->getRepository('AMiEOffreEmploiBundle:OffreEmploi')->findOld($dateOld); $offresOld = $query->getResult(); for ($i = 0; $i < sizeof($offresOld); $i++) { $em->remove($offresOld[$i]); $em->flush(); } switch ($actif) { case 'actif': $offres = $em->getRepository('AMiEOffreEmploiBundle:OffreEmploi')->findBy(array('actif' => 'A'), array('updatedDate' => 'DESC')); $pagerfanta = new Pagerfanta(new ArrayAdapter($offres)); $pagerfanta->setMaxPerPage($maxPerPage); try { $pagerfanta->setCurrentPage($page); } catch (NotValidCurrentPageException $e) { throw new NotFoundHttpException(); } break; case 'inactif': $offres = $em->getRepository('AMiEOffreEmploiBundle:OffreEmploi')->findBy(array('actif' => 'F'), array('updatedDate' => 'DESC')); $pagerfanta = new Pagerfanta(new ArrayAdapter($offres)); $pagerfanta->setMaxPerPage($maxPerPage); try { $pagerfanta->setCurrentPage($page); } catch (NotValidCurrentPageException $e) { throw new NotFoundHttpException(); } break; case 'tous': $offres = $em->getRepository('AMiEOffreEmploiBundle:OffreEmploi')->findBy(array(), array('updatedDate' => 'DESC')); $pagerfanta = new Pagerfanta(new ArrayAdapter($offres)); $pagerfanta->setMaxPerPage($maxPerPage); try { $pagerfanta->setCurrentPage($page); } catch (NotValidCurrentPageException $e) { throw new NotFoundHttpException(); } break; default: $offres = $em->getRepository('AMiEOffreEmploiBundle:OffreEmploi')->findBy(array('actif' => 'A'), array('updatedDate' => 'DESC')); $pagerfanta = new Pagerfanta(new ArrayAdapter($offres)); $pagerfanta->setMaxPerPage($maxPerPage); try { $pagerfanta->setCurrentPage($page); } catch (NotValidCurrentPageException $e) { throw new NotFoundHttpException(); } $actif = 'actif'; break; } return $this->render('AMiEOffreEmploiBundle:Offres:index.html.twig', array('layout' => $layout, 'actif' => $actif, 'offres' => $pagerfanta)); }
/** * Get paginated media items by request * * @param Request $request * * @return Pagerfanta */ public function getPaginatedByRequest(Request $request) { $qb = $this->getRepository()->createQueryBuilderFromRequest($request); $paginator = new Pagerfanta(new DoctrineORMAdapter($qb)); $paginator->setMaxPerPage($request->get('limit', 50)); $paginator->setCurrentPage($request->get('page', 1)); return $paginator; }
/** * Lists all ContactFormType entities. * */ public function indexAction(Request $request) { $queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder()->select('e')->from($this->getEntityName(), 'e')->orderBy('e.id', 'DESC'); $adapter = new DoctrineORMAdapter($this->alterListQuery($queryBuilder)); $data = new Pagerfanta($adapter); $data->setCurrentPage($request->query->get('page', 1)); return $this->render('ClasticContactFormBundle:Backoffice:index.html.twig', array_merge(array('data' => $data), $this->getTemplateData())); }
/** * @Route("/{page}", name="homepage", requirements={"page" = "\d+"}, defaults={"page" = "1"}) * @Method("GET") */ public function indexAction($page) { $adapter = new ArrayAdapter($this->getDoctrine()->getRepository('AppBundle:User')->userOrderByDateTimeDesc()); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(5); $pagerfanta->setCurrentPage($page); return $this->render('tablon/index.html.twig', ['users' => $pagerfanta, 'page' => $page]); }