简体   繁体   中英

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?

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;
    
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM