Symfony2表单query_builder - 允许null

时间:2013-06-29 21:04:47

标签: symfony doctrine-orm symfony-forms query-builder

在Symfony2表单中,当试图获取实体时,Symfony期望接收QueryBuilder对象,但有时没有返回实体。在这种情况下,会出现一条错误消息:

  

“Doctrine \ ORM \ QueryBuilder”类型的预期参数,“NULL”给出

如何使query_builder允许选项没有可用的实体。

$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();
}

实际上,它只是基本的$er->findBy(array('company' => $company))方法 但我使用自定义getClients()方法

1 个答案:

答案 0 :(得分:6)

你的Closure应该返回QueryBuilder对象,而不是它的结果。

您的 ClientRepository 应如下所示:

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

}

然后你需要在你的Closure中使用getClientQueryBuilder

$builder
    ->add('client', 'entity', array(
        'class'         => 'Faktura\FakturaBundle\Entity\Client',
        'query_builder' => function(\Web\MyBundle\Repository\ClientRepository $er) use ($company){
            return $er->getClientsQueryBuilder($company);
    ))
;