0

I'm doing something like that on my project:

use Doctrine\ORM\EntityRepository;

class ArticlesType extends AbstractType {
    static function statusFilter(EntityRepository $er) {
        return $er->createQueryBuilder('x')->where('x.status = 1');
    }


    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
                ->add('User', 'entity', array('class' => 'FP\MyBundle\Entity\Users',
#                                             'query_builder' => call_user_func(array('self','statusFilter'), ??)
                                              'query_builder' => function(EntityRepository $er) { return ArticlesType::statusFilter($er); }
                                             ))
    }
}

any ideas on how to do a "nicer" call to the statusFilter method?

As you can see, I gave it a try with call_user_func, but I don't know which parameter to pass to it

thanks

2 Answers 2

1

You can use

self::statusFilter($er);

Alternatively, you can use

call_user_func(array('self', 'statusFilter'), $er);

I understand this question better now. As @igorw suggest, Symfony is expecting a closure; however, this doesn't mean it can't be written nicer.

You could create a custom helper and then use it in your buildFom call.

function funcRef($func){
  return create_function('', "return call_user_func_array('{$func}', func_get_args());");
}

Then you could use it in your buildForm method as:

'query_builder' => funcRef("ArticlesType::statusFilter")

see it working here on tehplayground.com

Sign up to request clarification or add additional context in comments.

1 Comment

what I don't get is this $er variable / It seems it doesn't "exist" (ie, I can't pass it to the function, but when I do function(EntityRepository $er), it "appears"
0

No. Symfony\Bridge\Doctrine\Form\Type\EntityType takes the query_builder option and passes it on to the Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList.

The query builder needs to be either an instance of Doctrine\ORM\QueryBuilder or a Closure (anonymous function).

Also, call_user_func as suggested by macek would work in most cases, but it will not work in a closure, because it has a different scope. This might be addressed in PHP 5.4, but for now it will simply not work.

I would do it just as you have, using a closure and calling the static method from within it.

EDIT: And what you were initially trying to do won't work either, because in that case you would be calling the static method already. And that's not what you want. What you want is to pass a function, which is to be called at a later point in time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.