Query_builder Symfony form builder error

2019-07-10 02:32发布

问题:

I have an entity field in my form that shows all forms in the database in a list. These forms have revision numbers. What I want to do is to show only the last revision of a form as an option in the list.

To clarify, the form table looks like this

Id || Name || Revision_number

1  || Form1 || 1

2  || Form1 || 2

The select list should only show revision 2.

So far, I have tried this

->add('form', 'entity', array(
                'class' => 'AppBundle\Entity\Form',
                'label' => 'label.ship.form',
                'query_builder' => function(EntityRepository $er){
                    return $er->createQueryBuilder('f')
                        ->select('f, MAX(f.revisionNumber) AS max_revision');
                }
            ))

But I get this error

Warning: spl_object_hash() expects parameter 1 to be object, string given 

回答1:

I've faced this problem too.

'query_builder' option should return Doctrine\ORM\QueryBuilder or a Closure and in your case (someone correct me if I am wrong) the "select" method is supposed to return a Doctrine\ORM\QueryBuilder object too. Weird, right...

What I did was create a method in the entity repository that returns the query builder itself:

public function generateStaffRolesQB() {
    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb->select('r')
            ->from('DatabaseModelsBundle:Role', 'r')
            ->where('r.id IN (1, 2)');

    return $qb;
}

And in the form I use it like this:

'query_builder' => function(EntityRepository $er) {
    return $er->generateStaffRolesQB();
 },

Hope it helps.