Sonata Admin Bundle: show total count of collection on list view

前端 未结 5 943
孤城傲影
孤城傲影 2021-01-06 04:50

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?

5条回答
  •  太阳男子
    2021-01-06 05:20

    Show field it is quite easy, there is solution for sorting by this virtual field.

    1. Entity/Some.php more about count here Extra Lazy Associations

      public function getCommentsCount()
      {
          return $this->getComments()->count();
      }
      
    2. 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' => [],
                  ]
              )
           //....
       }
      
    3. service.yaml add "simple" paginator (count does not work correctly)

      tags:
          - { name: sonata.admin, pager_type: "simple", ...
      

    Reasons:

    • subquery in orm join is not allowed
    • subquery in orm orderBy is not allowed
    • HIDDEN field does not work

    \Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery::getFixedQueryBuilder (// for SELECT DISTINCT, ORDER BY expressions must appear in idxSelect list)

提交回复
热议问题