I don't know how to do it and I've been doing it for a while and I can't find a solution, as it says in the title, I don't know why at the time of filtering, the KNP_paginator, the links of the paginator, at the time of filtering are restarted. I can't find the solution and here is my code:
This is the controller of the entity where we render the index together with the filters:
/**
* @Route("/", name="coche_index", methods={"GET","POST"})
*/
public function index(CocheRepository $cocheRepository, Request $request): Response
{
//Está filtrando
$estaFiltrando = false;
$valueModelo = $request->request->get('term_modelo');
$valueMarca = $request->request->get('term');
$valueAno = $request->request->get('term_ano');
$valueActivo = $request->request->get('term_activo');
$valorActivo = 0;
if ($valueActivo == true || $valueActivo == 1) {
$valorActivo = 1;
} else {
$valorActivo = 0;
}
if ($valueModelo == null && $valueMarca == null && $valueAno == null && $valueActivo == null) {
$estaFiltrando = false;
} else {
$estaFiltrando = true;
}
$marcas = $cocheRepository
->todasLasMarcas();
$hayMarcas = false;
if ($marcas == null) {
$hayMarcas = false;
} else {
$hayMarcas = true;
}
$paginator = $this->get('knp_paginator');
if ($estaFiltrando == true) {
$cochesQuery = $cocheRepository
->findModeloMarcasAnosActivos($valueModelo, $valueMarca, $valueAno, $valorActivo);
// Paginate the results of the query
$coches = $paginator->paginate(
// Doctrine Query, not results
$cochesQuery,
// Define the page parameter
$request->query->getInt('page', 1),
// Items per page
3
);
} else {
$cochesQuery = $cocheRepository->findCochesMarcas();
// Paginate the results of the query
$coches = $paginator->paginate(
// Doctrine Query, not results
$cochesQuery,
// Define the page parameter
$request->query->getInt('page', 1),
// Items per page
3
);
}
return $this->render('coche/index.html.twig', [
'coches' => $coches,
'marcas' => $marcas,
'idMarca' => $valueMarca,
'valueAno' => $valueAno,
'valueModelo' => $valueModelo,
'valueActivo' => $valueActivo,
'hayMarcas' => $hayMarcas,
'estaFiltrando' => $estaFiltrando,
]);
}
Here is the repository where I do the query and the filtering:
/**
* @param $modelo
* @param $idMarca
* @param $ano
* @param $activo
* @return Coche[]
*/
public function findModeloMarcasAnosActivos($modelo, $idMarca, $ano, $activo)
{
$qb = $this->createQueryBuilder('c');
if ($modelo != null || $modelo != '') {
$qb
->andWhere("c.modelo LIKE :searchModelo")
->setParameter('searchModelo', $modelo);
}
if ($idMarca != null) {
$qb
->andWhere("c.marca = :searchTerm")
->setParameter('searchTerm', $idMarca);
}
if ($ano != null || $ano > 0) {
$qb
->andWhere("c.ano = :searchAno")
->setParameter('searchAno', $ano);
}
if ($activo != null || $activo >= 0) {
$qb
->andWhere("c.activo = :searchActivo")
->setParameter('searchActivo', $activo);
}
return $qb
->getQuery()
->getResult();
}
findModeloMarcasAnosActivos It is the method where I filter and call it in the controller. Then I assign that filter to the pager, if it is filtering, if not, it displays the index.
Twig index.html.twig
{% block body %}
<h1 class="text-center">Coches</h1>
<div class="container">
<form class="pb-3" name="form" method="post" action="{{ path('coche_index') }}">
<div id="form">
<label for="vehicle1">Filtrar por modelo</label>
{% if valueModelo is defined %}
<input type="text" name="term_modelo" id="form_term" value="{{valueModelo}}">
{% else %}
<input type="text" name="term_modelo" id="form_term">
{% endif %}
<span>Filtrar por Marca:
</span>
<select name="term" id="form_term">
<option value="">-- Selecciona una marca --</option>
{% for marca in marcas %}
{% if idMarca is defined and marca.id == idMarca %}
<option value="{{ marca.id }}" selected>{{ marca.nombre }}</option>
{% else %}
<option value="{{ marca.id }}">{{ marca.nombre }}</option>
{% endif %}
{% endfor %}
</select>
<label for="vehicle1">Filtrar año</label>
{% if valueAno is defined %}
<input type="number" name="term_ano" id="form_term" value="{{valueAno}}">
{% else %}
<input type="number" name="term_ano" id="form_term">
{% endif %}
<label for="vehicle1">Activo</label>
{% if valueActivo is defined and valueActivo == 1 or valueActivo == true %}
<input type="checkbox" id="vehicle2" name="term_activo" id="form_term" value="1" checked>
{% else %}
<input type="checkbox" id="vehicle2" name="term_activo" id="form_term" value="1">
{% endif %}
{% if estaFiltrando == true and estaFiltrando is defined %}
<span>Resultados de búsqueda por:
<strong>{{ idMarca }}</strong>
</span>
<button class="btn btn-primary" type="submit" id="form_save" name="save">Filtrar</button>
<p>
<a class="btn btn-danger" href="{{ path('coche_index') }}">Borrar filtro</a>
</p>
{% else %}
<button class="btn btn-primary" type="submit" id="form_save" name="save">Filtrar</button>
{% endif %}
</div>
</form>
<hr>
{% if app.user %}
{% if hayMarcas == true %}
<a class="btn btn-outline-primary" href="{{ path('coche_new') }}">Crear nuevo coche</a>
{% else %}
<span>No existe ninguna marca, debes de crear primero una marca!</span>
<a href="{{ path('marca_new') }}">Crear nueva marca</a>
{% endif %}
{% endif %}
<div class="row" id="coches">
{% for coche in coches %}
<div class="col-sm-4 p-2">
<div class="card text-center">
<img src="{{ asset ('uploads/coches/' ~ coche.imagenCoche) }}" class="card-img-top img-fluid" alt="...">
<div class="card-body">
<h3 class="card-title">{{ coche.nombre }}</h3>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">
<strong>Marca:</strong>
{{ coche.marca.nombre }}</li>
<li class="list-group-item">
<strong>Modelo:</strong>
{{ coche.modelo }}</li>
<li class="list-group-item">
<strong>Descripcion</strong>
{{ coche.descripcion }}</li>
<li class="list-group-item">
<strong>Fecha de alta:</strong>
{{ coche.fechaAlta|date("d/m/Y") }}</li>
<li class="list-group-item">
<strong>Año:</strong>
{{ coche.ano }}</li>
<li class="list-group-item">
<strong>Activo:</strong>
{% if coche.activo == 1 %}
Activo</li>
{% else %}
No activo</li>
{% endif %}
<li class="list-group-item">
<strong>Fecha de Modificacion:</strong>
{{ coche.fecha_modificacion|date() }}</li>
{% if app.user %}
<li class="list-group-item">
<div>
<a class="btn btn-outline-primary" href="{{ path('coche_show', {'id': coche.id}) }}">Ver</a>
<a class="btn btn-outline-primary" href="{{ path('coche_edit', {'id': coche.id}) }}">Editar</a>
{{ include('coche/_delete_form.html.twig') }}
</div>
</li>
{% endif %}
</ul>
</div>
</div>
{% else %}
<div class="col-sm-12 p-2">
<div class="card">
<div class="card-body">
<h3 class="card-title">No se ha encontrado ningún dato!</h3>
</div>
</div>
</div>
{% endfor %}
</div>
{% if app.user %}
{% if hayMarcas == true %}
<a class="btn btn-outline-primary" href="{{ path('coche_new') }}">Crear nuevo coche</a>
{% else %}
<span>No existe ninguna marca, debes de crear primero una marca!</span>
<a class="btn btn-outline-primary" href="{{ path('marca_new') }}">Crear nueva marca</a>
{% endif %}
{% endif %}
<div class="pagination justify-content-center">
{{ knp_pagination_render(coches) }}
</div>
</div>{% endblock %}
The pager is at the bottom and the form is at the top of the page.
Here is when I filter, 2 pages appear in the pager
EDIT
I will explain a little more about the pager:
I'm already calling the pager, in the code itself I make the sample of how to call it, however, this is not the problem I'm talking about, it's when I make the form, and I get the values from the form when filtering.
$valueModelo = $request->request->get('term_modelo');
$valueMarca = $request->request->get('term');
$valueAno = $request->request->get('term_ano');
$valueActivo = $request->request->get('term_activo');
Then I call the $paginator = $this->get('knp_paginator'); to get the paginator and then what I do is to filter, I put the query from the repository filter to the paginator:
$coches = $paginator->paginate(
// Doctrine Query, not results
$cochesQuery,
// Define the page parameter
$request->query->getInt('page', 1),
// Items per page
3
);
The problem is that the paginator, when I click on one of the links, it restarts and returns to the non-filtered paginator, in the images I also make the sample.
So you should use dependency injection first of all.
use Knp\Component\Pager\PaginatorInterface;
then in your function:
public function someNameAction(PaginatorInterface $paginator) {
}
You would pass your query ($qb) into $query and return $query instead of $qb. The 1 and 50 is part of the page numbers. Note: You can call that in another function and pass $paginator if that is how you are calling the function.