Search code examples
symfonysonata-admin

Show only country_id =1 in list (Symfony + Sonata)


This is my simple listing of the "News" entity

protected function configureListFields(ListMapper $list): void
{
    $list
        ->filte
        ->add('id')
        ->add('name')
        ->add('description')
        ->add('createdAt')
        ->add('updatedAt')
        ->add(ListMapper::NAME_ACTIONS, null, [
            'actions' => [
                'show' => [],
                'edit' => [],
                'delete' => []
            ],
        ]);
}

The News entity also has a country_id field (I won't show). I need show only the news with country_id = 1. How?


Solution

  • Ok, I solved with documentation

    protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
    {
        $query = parent::configureQuery($query);
    
        $rootAlias = current($query->getRootAliases());
    
        $query->andWhere(
            $query->expr()->eq($rootAlias . '.my_field', ':my_param')
        );
        $query->setParameter('my_param', 'my_value');
    
        return $query;
    }
    

    But need made several changes beacuse $query not is a QueryBuilder Object.

    protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
    {
    
        $query = parent::configureQuery($query);
    
        $query_qb = $query->getQueryBuilder();
        $rootAlias = current($query->getQueryBuilder()->getRootAliases());
    
        $query_qb->andWhere(
            $query_qb->expr()->eq($rootAlias . '.idCountry', ':idCountry')
        );
        $query_qb->setParameter('idCountry', $this->security->getUser()->getCountry()->getId());
    
        return $query;
        
    }