Search code examples
symfonypagerfanta

How to get the number of result? - Pagerfanta and Twig (in Symfony)


In my Demo application, use Pagerfanta to read only a few rows from Database.

public function findAllProductsByCategory($category, int $page = 1): Pagerfanta
{
    // DQL = Always select full classes from classes
    $query = $this->getEntityManager()
        ->createQuery('
             SELECT   p
             FROM     App\Entity\Product p
             WHERE    p.category = :category
        ')
        ->setParameter('category', $category);

    return $this->createPaginator($query, $page);
}

Later in Twig, I loop the preselected results. Everything is fine ...

    {% if products.haveToPaginate %}
        <div class="navigation text-center">
            {{ pagerfanta(products, 'default', {routeName: 'category_show_paginated', 'routeParams' : { 'id': category.id}}) }}
        </div>
    {% endif %}
    <table border="1" cellpadding="5">
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Products</th>
            <th>Description</th>
        </tr>
        {% for product in products %}
        <tr>
            <td>{{ loop.index }}</td>
            <td><a href="{{ path('products_show', {id: product.id}) }}">{{ product.name }}</a></td>
            <td>{{ product.description }}</td>
        </tr>
        {% endfor %}
    </table>

but on each page, "loop.index" is the same 1,2,3,4 ... I would like to show the number of results 41,42,43 ... with pagerfanta ;)

Is there a special function?

Thank you


Solution

  • Haven't worked with Pagerfanta for a while, but what you want should be doable with something like this:

    {{ pagerfanta.currentPageOffsetStart() + loop.index }}
    

    Example test case: https://hotexamples.com/examples/pagerfanta/Pagerfanta/getCurrentPageOffsetStart/php-pagerfanta-getcurrentpageoffsetstart-method-examples.html