Search code examples
symfonydoctrine-ormsql-order-bysonata-admin

Sonata Admin v2.3 - Order by on multiple columns with sortable = false


I have been using [this][1] solution to ORDER BY on multiple columns for version 2.2.* It has been working well for almost a year.

Recently upgraded to version 2.3.* and the list was not ordering the results any more.

I notice that if I set at least one column to be sortable things go back to normal. In my case I set all columns to 'sortable' => false yet I still want to see things in a specific order; I just don't want users to select the sorting order!

Any way to get this working again?


Solution

  • This is due to the following addition in the new version; the orderBy options are removed if ProxyQuery::getSortOrder() doesn't return anything.

    In this case the method is automatically called by the Datagrid::buildPager() IF AND ONLY IF the list configuration has at least one column set to 'sortable' => true, see DataGrid.php#L126. If all columns are not sortable the custom ORDER BY options will be removed!

    The only way to ORDER BYon multiple columns would be to ensure that the method ProxyQuery::setSortOrder is called at some point see ProxyQuery.php#140.

    I'm not sure if this is an unintended side-effect or it is how it was design to work.

    To work around this either set at least one column to 'sortable' => true (or don't set sortable at all) or modify the createQuery method in your admin class like so:

    public function createQuery($context = 'list')
    {
        $proxyQuery = parent::createQuery($context);
        // Default Alias is "o"
        $proxyQuery->orderBy('o.name', 'ASC');
        // This can only be used for a single column. 
        $proxyQuery->setSortBy([], ['fieldName' => 'date']);
        $proxyQuery->setSortOrder('DESC');
    
        return $proxyQuery;
    }