简体   繁体   English

如何使用 knp_paginator Symfony 4 过滤表单?

[英]How to filter a form with knp_paginator Symfony 4?

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.我不知道该怎么做,我已经做了一段时间了,我找不到解决方案,正如标题中所说,我不知道为什么在过滤时,KNP_paginator,重新启动过滤时分页器的链接。 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:这是我们将索引与过滤器一起呈现的实体的controller

/**
 * @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. findModeloMarcasAnosActivos就是我在controller中过滤调用的方法。 Then I assign that filter to the pager, if it is filtering, if not, it displays the index.然后我将该过滤器分配给寻呼机,如果它正在过滤,如果不是,它会显示索引。

Twig index.html.twig Twig 索引。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这是我过滤时,寻呼机中出现2页

When I click on page 2, the other pager appears and it is as if it restarts and the filter disappears.当我单击第 2 页时,会出现另一个寻呼机,就好像它重新启动并且过滤器消失了一样。 This is the failure I have... Any solution?这是我的失败......有什么解决办法吗?

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');然后我调用$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;使用 Knp\Component\Pager\PaginatorInterface;

then in your function:然后在你的 function 中:

public function someNameAction(PaginatorInterface $paginator) {公共 function someNameAction(PaginatorInterface $paginator) {

...Before you return $qb do the following:

$query = $paginator->paginate(
    $qb,
    1,
    50
);

} }

You would pass your query ($qb) into $query and return $query instead of $qb.您可以将查询 ($qb) 传递给 $query 并返回 $query 而不是 $qb。 The 1 and 50 is part of the page numbers. 1 和 50 是页码的一部分。 Note: You can call that in another function and pass $paginator if that is how you are calling the function.注意:您可以在另一个 function 中调用它并传递 $paginator,如果这是您调用 function 的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM