0

How to add sort by number of votes in admin?

I have a nominee entity with relation One To Many vote. I need to allow to sort by number of votes for nominees.

I try a solution from here: https://github.com/sonata-project/SonataAdminBundle/issues/1077 and first here: Sonata Admin Bundle: show total count of collection on list view

But I get error message: [Semantical Error] line 0, col 184 near 'v_id_count ASC,': Error: 'v_id_count' is not defined.

Here's the code from NomineeAdmin:

public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);

    if ('list' === $context) {
        $parameters = $this->getFilterParameters();

        if ('getVotesCount' === $parameters['_sort_by']) {
            $rootAlias = $query->getRootAliases()[0];

            $query
                ->addSelect('COUNT(v.id) as v_id_count')
                ->leftJoin($rootAlias . '. votes', 'v')
                ->groupBy($rootAlias . '.id')
                ->orderBy('v_id_count', $parameters['_sort_order']);

        }
    }

    return $query;
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        //...
        ->add(
            'getVotesCount',
            null,
            [
                'sortable'                         => true,
                'sort_field_mapping'               => ['fieldName' => 'id'],
                'sort_parent_association_mappings' => [],
            ]
        );
}
Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41
Oleg
  • 2,733
  • 7
  • 39
  • 62

1 Answers1

0

Have you tried to add a getter method within your entity to return the number of relation and used it as sort_field_mapping ?

getVotesNumber(): int { ... }

...

'sort_field_mapping' => ['fieldName' => 'votesNumber'],

I have not tried, but it should work (and this way, you won't have to make sql request)

  • This doesn't work. In this case I get an error: Type error: Argument 1 passed to Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery::entityJoin() must be of the type array, null given, called in /var/www/symfony/vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/ProxyQuery.php on line 143 – Oleg Dec 18 '19 at 16:20
  • This is probably because Symfony try to map the element, you can use https://symfony.com/doc/current/reference/forms/types/form.html#mapped false. – Yann Schepens Jan 02 '20 at 13:00