Skip to content

Instantly share code, notes, and snippets.

@jlchafardet
Created October 21, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlchafardet/a9cac678d56e6f690820209dc6ac1443 to your computer and use it in GitHub Desktop.
Save jlchafardet/a9cac678d56e6f690820209dc6ac1443 to your computer and use it in GitHub Desktop.
next and previous navigation for Entity Repository - Doctrine and Symfony (code for entity repository, controller, and twig template)
<?php
/**
* code of your controller
*/
#[Route('/{accountId}', name: 'controller_show', methods: ['GET'])]
public function show(Entity $entity, EntityManagerInterface $em): Response
{
$repo = $em->getRepository(Entity::class);
$id = $entity->getId();
$match = preg_replace('/[0-9]+/', '', entity->getAccountId());
return $this->render('entity_view/show.html.twig', [
'entityObject' => $entityObject,
'nav' => $repo->findNextPrevious($id, $match),
]);
}
<?php
# The word "Entity" in this file refers to your "Entity" class.
namespace App\Repository;
use "....."; # needed includes.
class EntityRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::_construct($registry, Entity::class);
}
/**
* anything you already had here
*/
public function findNextPrevious($id, $like)
{
$expr = $this->_em->getExpressionBuilder();
$next = $this->createQueryBuilder('a')
->select($expr->min('a.accountId'))
->where($expr->gt('a.id', ':id'))
->andWhere('a.accountId LIKE :like');
$previous = $this->createQueryBuilder('b')
->select($expr->max('b.accountId'))
->where($expr->lt('b.id', ':id'))
->andWhere('b.accountId LIKE :like');
$query = $this->createQueryBuilder('s')
->select('COUNT(s.id) as total')
->addSelect('(' . $previous->getDQL() . ') as previous')
->addSelect('(' . $next->getDQL() . ') as next')
->setParameter('id', $id)
->setParameter('like', '%' . $like . '%')
->getQuery();
return $query->getSingleResult();
}
}
{% extends ... %}
{% block body %}
.... whatever you print. ....
<div class="col-md-1 col-sm-1 col-1">
{% if nav.previous %}
<a href="{{ path('scholar_show', {'accountId': nav.previous }) }}"
class="btn btn-sm btn-primary">
<i class="fas fa-arrow-alt-circle-left"></i> Previous</a>
{% endif %}
</div>
<div class="col-md-1 col-sm-1 col-1">
{% if nav.next %}
<a href="{{ path('scholar_show', {'accountId': nav.next}) }}"
class="btn btn-sm btn-primary">
<i class="fas fa-arrow-alt-circle-right"></i> <br>Next</a>
{% endif %}
</div>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment