In Symfony2 forms, when trying to get entities, Symfony expects to receive QueryBuilder object, but sometimes there are no entities returned. In that case, an error message appears:
Expected argument of type "Doctrine\\ORM\\QueryBuilder", "NULL" given
How to make query_builder to allow option that there are no entities available.
$builder
->add('client', 'entity', array(
'class' => 'Faktura\FakturaBundle\Entity\Client',
'query_builder' => function(\Web\MyBundle\Repository\ClientRepository $er) use ($company){
return $er->getClients($company);
))
;
ClientRepository.php
public function getClients($company)
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where('c.company = :company')
->setParameter('company', $company)
->getQuery();
return $qb->getResult();
}
Actually, it's just basic $er->findBy(array('company' => $company))
method but I use custom getClients()
method
Your Closure should return QueryBuilder object, not results of it.
Your ClientRepository should look like:
public function getClients($company)
{
$qb = $this->getClientsQueryBuilder($company);
return $qb->getQuery()->getResult();
}
public function getClientsQueryBuilder($company)
{
return $this->createQueryBuilder('c')
->select('c')
->where('c.company = :company')
->setParameter('company', $company);
}
And then you need to use getClientQueryBuilder
in your Closure.
$builder
->add('client', 'entity', array(
'class' => 'Faktura\FakturaBundle\Entity\Client',
'query_builder' => function(\Web\MyBundle\Repository\ClientRepository $er) use ($company){
return $er->getClientsQueryBuilder($company);
))
;
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.