Giter Site home page Giter Site logo

knplabs / knppaginatorbundle Goto Github PK

View Code? Open in Web Editor NEW
1.7K 53.0 341.0 713 KB

SEO friendly Symfony paginator to sort and paginate

Home Page: http://knplabs.com/en/blog/knp-paginator-reborn

License: MIT License

PHP 62.99% Twig 37.01%
twig php paginator symfony symfony-bundle seo

knppaginatorbundle's Introduction

Intro to KnpPaginatorBundle

Friendly Symfony paginator to paginate everything

Build Status

Generally this bundle is based on Knp Pager component. This component introduces a different way of pagination handling. You can read more about the internal logic on the given documentation link.

knpbundles.com

Note: Keep knp-components in sync with this bundle. If you want to use older version of KnpPaginatorBundle - use v3.0 or v4.X tags in the repository which is suitable to paginate ODM MongoDB and ORM 2.0 queries

Latest updates

For notes about the latest changes please read CHANGELOG, for required changes in your code please read UPGRADE chapter of the documentation.

Requirements:

  • Knp Pager component >=2.0.
  • KnpPaginatorBundle's master is compatible with Symfony >=6.4 versions.
  • Twig >=3.0 version is required if you use the Twig templating engine.

Features:

  • Does not require initializing specific adapters.
  • Can be customized in any way needed, etc.: pagination view, event subscribers.
  • Possibility to add custom filtering, sorting functionality depending on request parameters.
  • Separation of concerns, paginator is responsible for generating the pagination view only, pagination view - for representation purposes.

Note: using multiple paginators requires setting the alias in order to keep non conflicting parameters.

More detailed documentation:

Installation and configuration:

Pretty simple with Composer, run

composer require knplabs/knp-paginator-bundle

Add PaginatorBundle to your application kernel

If you don't use flex (you should), you need to manually enable bundle:

// app/AppKernel.php
public function registerBundles()
{
    return [
        // ...
        new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
        // ...
    ];
}

Configuration example

You can configure default query parameter names and templates

YAML:

knp_paginator:
    page_range: 5                       # number of links shown in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links to page 4, 5, 6)
    default_options:
        page_name: page                 # page query parameter name
        sort_field_name: sort           # sort field query parameter name
        sort_direction_name: direction  # sort direction query parameter name
        distinct: true                  # ensure distinct results, useful when ORM queries are using GROUP BY statements
        filter_field_name: filterField  # filter field query parameter name
        filter_value_name: filterValue  # filter value query parameter name
    template:
        pagination: '@KnpPaginator/Pagination/sliding.html.twig'     # sliding pagination controls template
        rel_links: '@KnpPaginator/Pagination/rel_links.html.twig'     # <link rel=...> tags template
        sortable: '@KnpPaginator/Pagination/sortable_link.html.twig' # sort link template
        filtration: '@KnpPaginator/Pagination/filtration.html.twig'  # filters template

PHP:

// config/packages/paginator.php

<?php declare(strict_types=1);

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $configurator): void
{
    $configurator->extension('knp_paginator', [
        'page_range' => 5,                        // number of links shown in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links
        'default_options' => [
            'page_name' => 'page',                // page query parameter name
            'sort_field_name' => 'sort',          // sort field query parameter name
            'sort_direction_name' => 'direction', // sort direction query parameter name
            'distinct' => true,                   // ensure distinct results, useful when ORM queries are using GROUP BY statements
            'filter_field_name' => 'filterField', // filter field query parameter name
            'filter_value_name' => 'filterValue'  // filter value query parameter name
        ],
        'template' => [
            'pagination' => '@KnpPaginator/Pagination/sliding.html.twig',     // sliding pagination controls template
            'pagination' => '@KnpPaginator/Pagination/rel_links.html.twig',     // <link rel=...> tags template
            'sortable' => '@KnpPaginator/Pagination/sortable_link.html.twig', // sort link template
            'filtration' => '@KnpPaginator/Pagination/filtration.html.twig'   // filters template
        ]
    ]);
};

Additional pagination templates

That could be used out of the box in knp_paginator.template.pagination key:

  • @KnpPaginator/Pagination/sliding.html.twig (by default)
  • @KnpPaginator/Pagination/bootstrap_v5_pagination.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v4_pagination.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v3_pagination.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_pagination.html.twig
  • @KnpPaginator/Pagination/foundation_v6_pagination.html.twig
  • @KnpPaginator/Pagination/foundation_v5_pagination.html.twig
  • @KnpPaginator/Pagination/bulma_pagination.html.twig
  • @KnpPaginator/Pagination/semantic_ui_pagination.html.twig
  • @KnpPaginator/Pagination/materialize_pagination.html.twig
  • @KnpPaginator/Pagination/tailwindcss_pagination.html.twig
  • @KnpPaginator/Pagination/uikit_v3_pagination.html.twig

Sample rel link tag template

That could be used out of the box in knp_paginator.template.rel_links key:

  • @KnpPaginator/Pagination/rel_links.html.twig (by default)

Additional sortable templates

That could be used out of the box in knp_paginator.template.sortable key:

  • @KnpPaginator/Pagination/sortable_link.html.twig (by default)
  • @KnpPaginator/Pagination/bootstrap_v5_bi_sortable_link.html.twig
  • @KnpPaginator/Pagination/bootstrap_v5_fa_sortable_link.html.twig
  • @KnpPaginator/Pagination/bootstrap_v5_md_sortable_link.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v3_sortable_link.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v4_font_awesome_sortable_link.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v4_material_design_icons_sortable_link.html.twig
  • @KnpPaginator/Pagination/semantic_ui_sortable_link.html.twig
  • @KnpPaginator/Pagination/uikit_v3_sortable.html.twig

Additional filtration templates

That could be used out of the box in knp_paginator.template.filtration key:

  • @KnpPaginator/Pagination/filtration.html.twig (by default)
  • @KnpPaginator/Pagination/bootstrap_v5_filtration.html.twig
  • @KnpPaginator/Pagination/twitter_bootstrap_v4_filtration.html.twig

Usage examples:

Controller

Currently paginator can paginate:

  • array
  • Doctrine\DBAL\Query\QueryBuilder
  • Doctrine\ORM\Query
  • Doctrine\ORM\QueryBuilder
  • Doctrine\ODM\MongoDB\Query\Query
  • Doctrine\ODM\MongoDB\Query\Builder
  • Doctrine\ODM\PHPCR\Query\Query
  • Doctrine\ODM\PHPCR\Query\Builder\QueryBuilder
  • Doctrine\Common\Collection\ArrayCollection - any Doctrine relation collection including
  • ModelCriteria - Propel ORM query
  • array with Solarium_Client and Solarium_Query_Select as elements
// App\Controller\ArticleController.php

public function listAction(EntityManagerInterface $em, PaginatorInterface $paginator, Request $request)
{
    $dql   = "SELECT a FROM AcmeMainBundle:Article a";
    $query = $em->createQuery($dql);

    $pagination = $paginator->paginate(
        $query, /* query NOT result */
        $request->query->getInt('page', 1), /*page number*/
        10 /*limit per page*/
    );

    // parameters to template
    return $this->render('article/list.html.twig', ['pagination' => $pagination]);
}

View

In <head>:

{# rel links for pagination #}
{{ knp_pagination_rel_links(pagination) }}

In <body>:

{# total items count #}
<div class="count">
    {{ pagination.getTotalItemCount }}
</div>
<table>
    <tr>
        {# sorting of properties based on query components #}
        <th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
        <th{% if pagination.isSorted('a.title') %} class="sorted"{% endif %}>
            {{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}
        </th>
        <th{% if pagination.isSorted(['a.date', 'a.time']) %} class="sorted"{% endif %}>
            {{ knp_pagination_sortable(pagination, 'Release', ['a.date', 'a.time']) }}
        </th>
    </tr>

    {# table body #}
    {% for article in pagination %}
        <tr {% if loop.index is odd %}class="color"{% endif %}>
            <td>{{ article.id }}</td>
            <td>{{ article.title }}</td>
            <td>{{ article.date | date('Y-m-d') }}, {{ article.time | date('H:i:s') }}</td>
        </tr>
    {% endfor %}
</table>
{# display navigation #}
<div class="navigation">
    {{ knp_pagination_render(pagination) }}
</div>

Translation in view

For translating the following text:

  • %foo% name with translation key table_header_name. The translation is in the domain messages.
  • {0} No author|{1} Author|[2,Inf] Authors with translation key table_header_author. The translation is in the domain messages.

translationCount and translationParameters can be combined.

<table>
    <tr>
       {# sorting of properties based on query components #}
       <th>{{ knp_pagination_sortable(pagination, 'Id'|trans({foo:'bar'},'messages'), 'a.id' )|raw }}</th>
       <th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title')|raw }}</th>
       <th>{{ knp_pagination_sortable(pagination, 'Author'|trans({}, 'messages'), 'a.author' )|raw }}</th>
    </tr>

    <!-- Content of the table -->
</table>

Adding translation files

You can also override translations by creating a translation file in the following name format: domain.locale.format. So, to create a translation file for this bundle you need to create for instance KnpPaginatorBundle.tr.yaml file under project_root/translations/ and add your translations there:

label_previous: "Önceki"
label_next: "Sonraki"
filter_searchword: "Arama kelimesi"

If you set default translation for configuration accordingly:

framework:
    default_locale: tr

Symfony will pick it automatically.

Dependency Injection

You can automatically inject a paginator service into another service by using the knp_paginator.injectable DIC tag. The tag takes one optional argument paginator, which is the ID of the paginator service that should be injected. It defaults to knp_paginator.

The class that receives the KnpPaginator service must implement Knp\Bundle\PaginatorBundle\Definition\PaginatorAwareInterface. If you're too lazy you can also just extend the Knp\Bundle\PaginatorBundle\Definition\PaginatorAware base class.

⚠ Warning using PaginatorAwareInterface is discouraged, and could be removed in a future version. You should not rely on setter injection, but only on proper constructor injection. Using Symfony built-in autowiring mechanism is the suggested way to go.

Lazy service

The knp_paginator service will be created lazily if the package symfony/proxy-manager-bridge is installed.

For more information about lazy services, consult the Symfony documentation on dependency injection.

XML configuration example
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="my_bundle.paginator_aware.class">MyBundle\Repository\PaginatorAwareRepository</parameter>
    </parameters>

    <services>
        <service id="my_bundle.paginator_aware" class="my_bundle.paginator_aware.class">
            <tag name="knp_paginator.injectable" paginator="knp_paginator" />
        </service>
    </services>
</container>

Troubleshooting

  • Make sure the translator is activated in your Symfony config:
framework:
    translator: { fallbacks: ['%locale%'] }
  • If your locale is not available, create your own translation file in translations/KnpPaginatorBundle.en.yml (substitute "en" for your own language code if needed). Then add these lines:
label_next: Next
label_previous: Previous
  • Note that <rel> links are only meaningful when using pagination, they are not relevant to sorting or filtering.

Maintainers

Please read this post first.

This library is maintained by the following people (alphabetically sorted) :

  • @garak
  • @polc

knppaginatorbundle's People

Contributors

afolabiolayinka avatar andreybolonin avatar crackcomm avatar daria-sieroshtan avatar demontpx avatar docteurklein avatar garak avatar herzult avatar inoryy avatar jawadmjn avatar johnwards avatar ker0x avatar kocal avatar l3pp4rd avatar loostro avatar marcelorodrigo avatar mbontemps avatar mfurdyk avatar nicolasmure avatar ornicar avatar ostrolucky avatar pilot avatar polc avatar rafalwrzeszcz avatar roukmoute avatar stloyd avatar stof avatar toberger avatar torbenlundsgaard avatar xwb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

knppaginatorbundle's Issues

Undefined index: parent on complex query

I have this query: http://pastebin.com/hr6xD8LP which returns what I need in DQL while using Doctrine 2.2.0-DEV, but when I want to paginate it, I get this notice:

Notice: Undefined index: parent in /www/footageshare/vendor/knp-
components/src/Knp/Component/Pager/Event/Subscriber/Paginate/Doctrine/ORM/Query/CountWalker.php line
49

Add default items_per_page & page_range as a bundle parameter

Right now the Paginator's paginate function always has 10 as a default for items per page:

public function paginate($target, $page = 1, $limit = 10, $options = array())
    { ... }

Would be nice to be able to set your own default as a parameter of the bundle's configuration. Same for the page range

// File: app/configs/parameters.yml

parameters:
  knp_paginator.template.pagination: MyBundle:Pagination:pagination.html.twig
  knp_paginator.template.sortable:   MyBundle:Pagination:sortable.html.twig
  knp_paginator.paginator.items_per_page: 25
  knp_paginator.paginator.page_range: 8

Error when installing vendors

Hi guys,

I get this when running php bin/vendors install:

[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "templating" under "knp_paginator"

Thanks for help

Add support for Doctrine\ORM\QueryBuilder

Can you add support for Doctrine\ORM\QueryBuilder pagination?
To paginate Doctrine\ORM\Query objects we have to build entity repositories that returns Query objects instead of the usual results.
I guess that it could be simple, since you can get a Query from a QueryBuilder.

Problem "Alias" with group by function (sum)

I want to get a list of orders

Error

Notice: Undefined index: parent in 
vendor/bundles/Knp/Bundle/PaginatorBundle/Query/TreeWalker/Paginate/CountWalker.php line 49 

My code

    $dql = "SELECT o, op, SUM(op.quantity) AS co 
        FROM DATABundle:Orders o JOIN o.orderProduct op 
        GROUP BY op.order 
        ORDER BY co DESC";
    $em->createQuery($dql);
    $adapter = $this->get('knp_paginator.adapter');
    $adapter->setQuery($query);
    $adapter->setDistinct(true);
    $paginator = new \Zend\Paginator\Paginator($adapter);
    $paginator->setCurrentPageNumber($this->get('request')->query->get('page', 1));
    $paginator->setItemCountPerPage(5);
    $paginator->setPageRange(5);

Example needed on custom filtering/sorting

In the README, there is mention of the ability to add custom filtering and sorting based on the request parameters.

It might be worthwhile adding an example or two of how to use custom filtering and sorting with the PaginatorBundle.

Translating the sortable words

How can I mix it with translations in the views? It seems that is not possible to use the {% trans %} and pagination blocks together.

getPaginationData() -> public?

I need to the access to pagination data in the view. I want to generate numbers but
without using primary keys.

In order to use the result of paginationData() method I call it in the action and pass it to the view:

//MyBundle/Controller/DefaultController.php
public function indexAction($page)
{
    ...
    return array(
        'pagination' => $pagination,
        'pagination_data' => $pagination->getPaginationData()
    );
}

and then use it in the view:

//MyBundle/Resources/views/Default/index.html.twig
<tr {% if loop.index is odd %}class="color"{% endif %}>
    <td>{{ pagination_data.firstItemNumber + loop.index - 1}}</td>
    <td>{{ item.name }}</td>
</tr>

That's why I suggest to change getPaginationData() to public.

In its standard configuration, the paginator indirectly exposes internal structure to potential attackers

Using the paginator with the default settings provided on the documentation, the url generated by twig's paginator|sortable('Field Label', 'a.field') is composed of the called route with added parameters `?sort=a.field&direction=asc'.

The issue is that there's no restrictions on which field it can use : if I replace a.field by a.anotherField in the sort parameter of the url, the route is still valid and my data is sorted on that criteria.

And if I put a field name that do not exists on the model, an error is raised (instead of silently fail). Consequently, I know that the table hasn't got this field. An attacker - maybe using a dictionary - could then quickly determinate the profile of my table. Moreover, in some edges cases, playing with ascand desc, might event give him hints on the contents given the sort result...

I think that a database field isn't something that should be publicly exposed, not to mention a way to profile an entire table. It would be safer if we somehow provided the paginator with an array of sorting labels mapped to those fields and allow explicitly only these ones to be used for sort criterias.

Problem to include pagination in an other controller

Hello,
I have a problem only when I try to include a controller with pagination, in another.

{% block product %}
            {% render "ShopBundle:Product:list" %}
        {% endblock %}
An exception has been thrown during the rendering of a 
template ("Route "_internal" does not exist.") in KnplabsPaginatorBundle:Pagination:sliding.html.twig at line 20. 

I use symfony2 master branch, Have you ever seen this problem?
Thanks

Symfony2 Deps error

I have added the git repos to my deps file. After running bin/vendors install I am receiving the following errors:

Installing/Updating knp-components
Cloning into '/Users/shawn/Documents/work/sites/adaptive/drumhill/vendor/knp-components'...
fatal: https://github.com/knplabs/knp-components.git/info/refs not found: did you run git update-server-info on the server?
sh: line 0: cd: /Users/shawn/Documents/work/sites/adaptive/drumhill/vendor/knp-components: No such file or directory
sh: line 0: cd: /Users/shawn/Documents/work/sites/adaptive/drumhill/vendor/knp-components: No such file or directory
Installing/Updating KnpPaginatorBundle
Cloning into '/Users/shawn/Documents/work/sites/adaptive/drumhill/vendor//bundles/Knp/Bundle/PaginatorBundle'...
fatal: https://github.com/knplabs/KnpPaginatorBundle.git/info/refs not found: did you run git update-server-info on the server?
sh: line 0: cd: /Users/shawn/Documents/work/sites/adaptive/drumhill/vendor//bundles/Knp/Bundle/PaginatorBundle: No such file or directory
sh: line 0: cd: /Users/shawn/Documents/work/sites/adaptive/drumhill/vendor//bundles/Knp/Bundle/PaginatorBundle: No such file or directory

I can manually clone the repos into my vendor/ folder and then run bin/vendor install and It says I am at the current head for both knp-components and paginator

Fatal Error

Fatal error: Class Knplabs\PaginatorBundle\KnplabsPaginatorBundle contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\HttpKernel\Bundle\BundleInterface::getNamespace, Symfony\Component\HttpKernel\Bundle\BundleInterface::getPath) in /src/Knplabs/PaginatorBundle/KnplabsPaginatorBundle.php on line 26

Any idea on this?

Doesn't work with forwards

I haven't looked into it, so I'll just paste my use case:

Controller:

/**
 * @Extra\Route(name="offer_index")
 * @Extra\Template()
 */
public function indexAction($offer = null)
{
    if (!$offer instanceOf Offer) $offer = new Offer();

    $form = $this->get('form.factory')->create(new OfferType(), $offer);
    $formHandler = $this->get('form.handler')->create(new OfferHandler(), $form);

    // process form
    if ($formHandler->process()) {
        $this->get('session')->setFlash('notice', 'Success!');
        return $this->redirect($this->generateUrl('offer_index'));
    }

    return array(
        'form' => $form->createView(),
        'offers' => $this->_getOffers()
    );
}

/**
 * @Extra\Route("/{id}/edit", name="offer_edit")
 * @Extra\Template()
 */
public function editAction(Offer $offer)
{
    return $this->forward('OffersMainBundle:Offer:index', array('offer' => $offer));
}

And in my view:

{% block content %}
<div class="form-box">
    <h2>Offer Panel</h2>
    <form action="{{ path('offer_index') }}" method="post" novalidate="novalidate">
        {{ form_errors(form) }}

        {{ form_rest(form) }}
        <div class="buttons">
            <input type="submit" value="Save" />
            <input type="reset" value="Cancel" />
        </div>
        <br class="clear" />
    </form>
</div>

<table>
    <tr class="header">
        <th>{{ offers|sortable('Name', 'o.name') }}</th>
        <th>{{ offers|sortable('Post Url', 'o.postUrl') }}</th>
        <th>{{ offers|sortable('Daily Cap', 'o.dailyCap') }}</th>
        <th>{{ offers|sortable('Active?', 'o.active') }}</th>
        <th>Edit</th>
    </tr>
    <tr class="line">
        <td colspan="5"><div></div></td>
    </tr>
{% for offer in offers %}
    <tr {% if loop.index is even %}class="alt"{% endif %}>
        <td>{{ offer.name }}</td>
        <td>{{ offer.postUrl }}</td>
        <td>{{ offer.dailyCap }}</td>
        <td>{% if offer.active == 1 %}Yes{% else %}No{% endif %}</td>
        <td>
            <a href="{{ path('offer_creative', { 'id': offer.id }) }}">Creatives</a>
            <a href="{{ path('offer_edit', { 'id': offer.id }) }}">Edit</a>
        </td>
    </tr>
{% else %}
    <tr>
        <td colspan="2">Add an offer to get started!</td>
    </tr>
{% endfor %}
</table>

{{ offers|paginate }}

{% endblock %}

Basically when forwarding, I get the following error:

"An exception has been thrown during the rendering of a template ("Route "" does not exist.") in OffersMainBundle:Offer:index.html.twig at line 22."

I thought I'd submit this use case because a lot of people will be utilizing a similar system.

I love what this paginator was doing before I ran into this block and now it won't be appropriate for what I need it for.

Feature request: Need a little design touch

Can we add the two UTF chars ( and ) to the sort links when sorting by columns is active?

Example

  • First name - sorting default
  • First name ↓ - sorting asc
  • First name ↑ - sorting desc

That can be a nice interface touch.

Better configuration options

I would like to move configuration from parameters.yml to config.yml. Is following schema ok for you? Configuration would be optional (default values).

knp_paginator:
     template:
          pagination:
          sortable:
     page_range:

And before PR I wantend to ask if suggested improvement would be accepted.

packagist

register this package and its dependencies at packagist.

Refactoring

Paginator will be refactored as a base component and a bundle

Fatal error: Call to undefined method Symfony\Bundle\FrameworkBundle\ContainerAwareEventDispatcher::addSubscriberService() in /var/www/sf/Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 891

Hi!
I'm getting an error with the latest versions of KnpPaginatorBundle & Symfony2 (2.0.6).
Perhaps it's a bug ?

Fatal error: Call to undefined method Symfony\Bundle\FrameworkBundle\ContainerAwareEventDispatcher::addSubscriberService() in /var/www/sf/Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 891

Support for addWhere clause in QueryBuilder.

Hi Gediminas, didn't know you were supporting this Bundle, it is very nice, it saved me a lot of time.

I'm having an issue closely related to issue #15. When executing it trhows "Error producing an iterator"

By now I'm using $adapter->setDistinct(false); (as adviced in #15, it works very well).

This is the query:

$query = $this->getEntityManager()->createQueryBuilder();
        $query->select('c, b')
                    ->from('HotelBundle:Category', 'c')
                    ->leftJoin('c.bedrooms', 'b')
                    ->where($query->expr()->not($query->expr()->eq('c.name', ':name')))
                    ->setParameter('name', 'not available')  
                ;

        return $query->getQuery();

While you take it a look, I can try to PR, but that would be on weekend, as I have to submit my project prototype on Friday :@.
I'm in a hurry checking everything twice XD (Tell you this cuase I enjoy PR ;)

See you soon.

WhereInWalker removes any where clause.

There is a problem when distinct = true with WhereInWalker, it removes any previously created where clause in the AST, i.e

Constructed query:

  • SELECT j FROM job WHERE j.expires_at > '2000-01-01'
    should be after whereInWalker
  • SELECT j FROM job WHERE j.expires_at > '2000-01-01' AND id IN ( 1, 19 , ..)
    but
  • SELECT j FROM job WHERE id IN ( 1, 19 , ..)
    is created, raising a QueryException because number of arguments doesn't match.

I've bee taking a look at the code, but AST creations is to hard and confusing to me right now.

Thanks.

fatal: http://github.com/knplabs/KnpPaginatorBundle.git/info/refs not found

Hi,
I added KnpPaginatorBundle in deps file, but when I launch " bin/vendors install --reinstall" error is"

Installing/Updating knp-components
Cloning into /opt/lampp/htdocs/xxxx/vendor/knp-components...
fatal: http://github.com/knplabs/knp-components.git/info/refs not found: did you run git update-server-info on the server?
cd: 1: can't cd to /opt/lampp/htdocs/xxxx/vendor/knp-components

I updated server with " git update-server-info "

Can you help me?

Event and dispatcher based improvements

  • By default use core symfony eventdispatcher, will prevent creating new one
  • Use public properties for events, to avoid array option copies, optimize this part where possible

Incorrect Parameters in Pagination Query

I recently did a vendor update on my symfony2 project and some of my paginators stopped working. I tracked it down to the pagination query.

The first query is:

SELECT DISTINCT u0_.id AS id0, w1_.id AS id1 FROM widget w1_, user u0_ INNER JOIN user_newspapers u3_ ON u0_.id = u3_.user_id INNER JOIN newspaper n2_ ON n2_.id = u3_.newspaper_id WHERE u0_.id = ? AND w1_.newspaper_id = n2_.id ORDER BY w1_.id ASC LIMIT 20 OFFSET 0
Parameters: [11]

This returns 2 rows:
11,7
11,12

The next query that is run is:

SELECT w0_.id AS id0, w0_.name AS name1, w0_.size AS size2, w0_.theme AS theme3, w0_.created_at AS created_at4, w0_.updated_at AS updated_at5, w0_.analytics AS analytics6, w0_.newspaper_id AS newspaper_id7 FROM widget w0_, user u1_ INNER JOIN user_newspapers u3_ ON u1_.id = u3_.user_id INNER JOIN newspaper n2_ ON n2_.id = u3_.newspaper_id WHERE u1_.id = ? AND w0_.newspaper_id = n2_.id AND w0_.id IN (?, ?) ORDER BY w0_.id ASC
Parameters: [11, '11', '11']

The parameters should be [11,7,12] and that was the querying being run before I updated my vendors directory. I know that my Zend library was updated during the vendors update. Did something change in Zend to break the KnpPaginatorBundle?

Remove Zend dependency

I think it will be great to remove ZF Dependency, 150mo for just the Paginator it's kind of heady no?

What do you think about that ? :)

Plugin by name 'Sliding' was not found

Hi,

i'm getting the following exception

"Plugin by name 'Sliding' was not found in the registry; used paths:
Zend\Paginator\ScrollingStyle\: Zend/Paginator/ScrollingStyle/

for the twig line

{{ paginator_render(paginator)|raw }}

The file "Zend/Paginator/ScrollingStyle/Sliding.php" exists. Any idea what i'm missing here ?

Non-existent service error on prod

Hello,

I encounter the following issue only in production mode:

You have requested a non-existent service "knp_paginator.adapter".

I've tested on several environments and follow all the instruction in the documentation.

Everything is working fine with the app_dev.php

Thanks

Support For Doctrine\ORM\NativeQuery

When you used Zend\Paginator as Base Paginator I can use ArrayAdapter for NativeQuery results, but now i don't know how to paginate results from NativeQuery. Maybe you should think about NativeQuery support or ArrayCollection paginator?

Order by / Distinct vs. Postgresql

While trying to use the KnpPaginatorBundle with a postgresql I've encountered following error:

PDOException: SQLSTATE[42P10]: Invalid column reference: 7 ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1:
...LEFT JOIN tag t1_ ON t1_.id = p2_.tag_id ORDER BY p0_.name A...
^

Offending query is:

SELECT DISTINCT p0_.id AS id0 FROM p0_ LEFT JOIN tag p2 ON p0_.id = p2_.id LEFT JOIN tag t1 ON t1_.id = p2_.tag_id ORDER BY p0_.name ASC LIMIT 8
OFFSET 0

Simply trying to sort by art.name, but the psql doesn't like ORDER BY field without that field in select list.

Sluggable entity

Hi,
I've a problem with paginator.
When I tried to print slug field with paginator this is empty.
If I print slug firld non in paginator this contain the value.
Do you can help me?

Some listener must process an event during the "count" method call

I've emailed l3pp4rd about this directly but the more I think about it the more I think creating an issue might help others.

I am getting this error:
"Some listener must process an event during the "count" method call"

Which is in the count method of the Doctrine adapter.

My action code is the following:
$query = $this->odm->createQueryBuilder('WhiteOctober\FormBuilderBundle\Document\FormBuilder')->getQuery();
$this->pager->setQuery($query);
$paginator = new \Zend\Paginator\Paginator($this->pager);
$paginator->setCurrentPageNumber($this->request->query->get('page', 1));
$paginator->setItemCountPerPage(10);
$paginator->setPageRange(5);

The error is caused by the setItemCountPerPage but if I remove that call i get the same error in the templates.

I have been into Event/Listener/ODM/Paginate.php and the code is getting this far, and it is returning the expected value of "10" however if I change the value to 5 $paginator->setItemCountPerPage(5); the value remains as 10. So something is up.

Any clues?

when included through twig routing throws error

I have a twig page including another controller through the {% render() %} function.

In the included controller I render a template that includes the pagination render function.

I get an error on sliding.html.twig that there's no route for "" (empty route)

To solve the problem I changed the template a bit

I changed this on lines 7,13,20,30 and 36
{{ path(route, query|merge({'page': next})) }}

to this: (of course the param next should be changed to first/previous/page/last)
{{ route ? path(route, query|merge({'page': next})) : "?page="~next }}

To get this to work I also needed to give the second parameter (page) to the paginate() function directly from _GET() -- since it's not gotten correctly from either $request->query or $request itself.

The solution I used may just be a quickfix. Probably there's also a better solution to this.

Installation Instructions

didn't work for me, got the message

git submodule add git://github.com/zendframework/zf2.git vendor/Zend
fatal: Not a git repository (or any of the parent directories): .git

Using clone did work, though. I had installed sf2-rc4 by downloading a zip file, then using git to install the vendors.

Paginate route

Hi all.
How to set custom route for pagination?

Now its look "/articles/index.html?page={page}"

but I need to /articles/page/{page}.html

need help to adopt v1.0 to doctrine2.2

I have an error using v1.0 with doctrine2.2

Fatal error: Call to undefined method Doctrine\ORM\Query\AST\PathExpression::isSimpleArithmeticExpression() in C:\wamp\www\tonic2\vendor\doctrine-2.2\lib\Doctrine\ORM\Query\SqlWalker.php on line 2026

Please help to resolve an issue

Many thanks.

Doctrine error when adding and andWhere to clause

Hi

Not sure if this is one for you or one for Doctrine, but we get this error when adding an additional "andWhere" clause to our base query when using the Paginator:

Fatal error: Call to undefined method Doctrine\ORM\Query\AST\ConditionalTerm::isSimpleConditionalExpression() in /home/daniel/www/yProx/vendor/doctrine/lib/Doctrine/ORM/Query/SqlWalker.php on line 1414

Single id is not allowed

I'm receiving this exception when trying to load paginator.

"Single id is not allowed on composite primary key in entity Application\GeneralBundle\Entity\Classis"

I've got four @id in my Entity wich I need for my @oneToMany associations to other Entities.

Deleting those @id from my Entity solves this Issue, but.... I really need those Ids!!

Any idea?

Thanks!

Pagination in an action reached through a forward

For some reason $this->route in the SlidingPaginationSubscriber is never set, when the Action instantiation the paginator is reached through a forward:

An exception has been thrown during the rendering of a template ("Route "" does not exist.") in _:_:index.html.twig at line 48.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: RouteNotFoundException »

Line 48 of the template is:
{{ entities.sortable('name', 'e.name')|raw }}

Using DelegatingEngine in helper gives error

Error is:
Argument 1 passed to Knplabs\PaginatorBundle\Templating\Helper\PaginationHelper::__construct() must be an instance of Symfony\Component\Templating\DelegatingEngine, instance of Symfony\Bundle\TwigBundle\TwigEngine

If I change the service to be the delegating engine it fails to work. If I remove the type hinting the helper works fine.

Doctrine/DQL - two items in FROM not supported

problem:
DQL supports unrelated entities by something like that:
'FROM Entity1 w, Entity2 l'
But it doesn't seems to work, every time I have an error (error below).

The problem appear when you need to make connection with unrelated (directly) entities,
eg:
Entity1(
ID
TagID REFERENCES Tag(ID)
)

Entity2(
ID
TagID REFERENCES Tag(ID)
)

Tag(
ID
Name
)

Only way to make it via Doctrine is to use FROM with two entities or NativeQuery...

error:
Warning: current() expects parameter 1 to be array, boolean given in /
var/www/Symfony/vendor/bundles/Knp/Bundle/PaginatorBundle/Event/
Listener/ORM/Paginate.php line 54

Add suport for DBAL QueryBuilder

Now it is only possible to paginate ORM/ODM queries, or arrays, can You add support for paginating of Doctrine\DBAL\Query\QueryBuilder ?

no results for unsual query

I have a query that looks like this

SELECT u FROM ProjectUpdatesBundle:Update u, ProjectFriendsBundle:Friend f
WHERE u.is_news = TRUE AND f.owner = u.persona AND f.friend = ?1
ORDER BY u.created_at DESC

Now I know that usually with doctrine we'll do innerJoins, but in this case I have tried several things (like creating a oneToMany relation), but it all isn't working, while this query is giving me the right results.

Only problem is that it doesn't show any results through the paginate() function...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.