首页 > 解决方案 > 如何使用 knp_paginator Symfony 4 过滤表单?

问题描述

我不知道该怎么做,我已经做了一段时间了,我找不到解决方案,正如标题中所说,我不知道为什么在过滤时,KNP_paginator,重新启动过滤时分页器的链接。我找不到解决方案,这是我的代码:

这是我们与过滤器一起呈现索引的实体的控制器:

/**
 * @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,
    ]);
}

这是我进行查询和过滤的存储库:

/**
 * @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是我在控制器中过滤和调用的方法。然后我将该过滤器分配给寻呼机,如果它正在过滤,如果不是,它会显示索引。

树枝 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 %}

寻呼机位于底部表单位于页面顶部。

这是我过滤时,寻呼机中出现2页

当我单击第 2 页时,会出现另一个寻呼机,就好像它重新启动并且过滤器消失了一样。这是我的失败......有什么解决办法吗?

编辑

我将进一步解释寻呼机:

我已经在调用寻呼机,在代码本身中我制作了如何调用它的示例,但是,这不是我要谈论的问题,而是在我制作表单时,我从表单中获取值过滤时。

 $valueModelo = $request->request->get('term_modelo');
 $valueMarca = $request->request->get('term');
 $valueAno = $request->request->get('term_ano');
 $valueActivo = $request->request->get('term_activo');

然后我调用$paginator = $this->get('knp_paginator'); 要获取分页器,然后我要做的是过滤,我将查询从存储库过滤器放到分页器:

        $coches = $paginator->paginate(
        // Doctrine Query, not results
        $cochesQuery,
        // Define the page parameter
        $request->query->getInt('page', 1),
        // Items per page
        3
    );

问题是分页器,当我单击其中一个链接时,它会重新启动并返回到未过滤的分页器,在图像中我也制作了示例。

标签: phpmysqlsymfonyfilterknppaginator

解决方案


所以你应该首先使用依赖注入。

使用 Knp\Component\Pager\PaginatorInterface;

然后在你的函数中:

公共函数 someNameAction(PaginatorInterface $paginator) {

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

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

}

您可以将查询 ($qb) 传递给 $query 并返回 $query 而不是 $qb。1 和 50 是页码的一部分。注意:您可以在另一个函数中调用它并传递 $paginator 如果这是您调用该函数的方式。


推荐阅读