Is there any way to show total count of collection on list view? Imagine that there is a user that can have many links. How can I show total links count on list view?
Show field it is quite easy, there is solution for sorting by this virtual field.
Entity/Some.php more about count here Extra Lazy Associations
public function getCommentsCount()
{
return $this->getComments()->count();
}
SomeAdmin.php override createQuery and configure list field
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
if ('list' === $context) {
$rootAlias = $query->getRootAliases()[0];
//...
$parameters = $this->getFilterParameters();
if ('getCommentsCount' === $parameters['_sort_by']) {
$query
->leftJoin($rootAlias.'. comments', 'cm')
->groupBy($rootAlias.'.id')
->orderBy('COUNT(cm.id)', $parameters['_sort_order'])
;
}
//...
}
return $query;
}
/**
* @param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
//...
->add(
'getCommentsCount',
null,
[
'sortable' => true,
'sort_field_mapping' => ['fieldName' => 'id'],
'sort_parent_association_mappings' => [],
]
)
//....
}
service.yaml add "simple" paginator (count does not work correctly)
tags:
- { name: sonata.admin, pager_type: "simple", ...
Reasons:
\Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery::getFixedQueryBuilder (// for SELECT DISTINCT, ORDER BY expressions must appear in idxSelect list)