Sorting on multiple columns in Sonata Admin

Recently, I have been developing again in Symfony2 using the Sonata AdminBundle. Yet again, I have stumbled on things that I thought were pretty common and easy, but I found it was very hard to find solutions for it. It even meant I had to dive into the code of the bundle, which I learned a lot from by the way, but I’d rather not had to do that for these “simple” tasks.

Therefore, I am going to write it down in a blogpost. But instead of doing one large blogpost, I will make it a series of multiple smaller blogposts to give you something to look out for.

Let’s start with the first one, which is about sorting on multiple columns in the list view. As you may, or may not know, it’s fairly easy to sort on one specific column, adding the following to your admin class:

 * Default values to the datagrid
 * @var array
protected $datagridValues = array(
    '_page'       => 1,
    '_sort_by'    => 'name',
    '_sort_order' => 'ASC'

The above code will make sure the admin class is sorted ascending on name in the list view, instead of the default id column sorting. Now, if we want to sort on multiple columns, it’s not possible to just add them in the sort_by unfortunately. Instead you should override the following method in your admin class:

     * Override to order products by name and creationdate
     * @param string $context
     * @return \Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery 
    public function createQuery($context = 'list')
        $queryBuilder = $this->getModelManager()->getEntityManager($this->getClass())->createQueryBuilder();
                             ->from($this->getClass(), 'p')
                             ->orderby(', p.creation_date');
        $proxyQuery = new ProxyQuery($queryBuilder);
        return $proxyQuery;

This example illustrates a product entity that is sorted by name and creation_date. This is the easiest way I have found to achieve this. If you know of a better way, let me know!

This entry was posted in PHP and tagged , , , . Bookmark the permalink.

4 Responses to Sorting on multiple columns in Sonata Admin

  1. Goran says:

    Better method: fork sonata and change those ugly _sort_by & _sort_order with something like _sort array.

    $datagridValues['_sort'] = array(
    ‘field1′ => ‘ASC’,
    ‘field2′ => ‘DESC’,

  2. Pingback: Sorting on multiple columns in Sonata Admin ← Bookmarks

  3. Thanks, this site is very helpful.|

  4. Thanks a ton! It is an superb internet site!|

Leave a Reply

Your email address will not be published. Required fields are marked *