Jooni Joon Jooni Joon - 7 months ago 148
PHP Question

How to get doctrine repository in form type in Symfony?

I am trying to use Doctrine in form type class.

Here is the Code

class UserType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options)

$userRepository= $this->getDoctrine()->getRepository('UserBundle:User');
$user = $userRepository->findOneByName('Sara');

->add('user', 'text', array(
'' => $user,
'label' => 'User',
->add('save', 'submit', array('label' => 'SoapServer'))

I am getting an error like this:

Attempted to call an undefined method named "getDoctrine" ...

Is there anyway to call doctrine?


I feel really ashamed about sharing this answer, but if you are desperate you can use something like this. Please, try to avoid this solution and find something nicer, without any global variables. Also, note that you have changed the repository var from $userRepository to $statusRepository.

public function buildForm(FormBuilderInterface $builder, array $options)
        global $kernel;

        if ( 'AppCache' == get_class($kernel) )
            $kernel = $kernel->getKernel();
        $doctrine = $kernel->getContainer()->get( 'doctrine' );

        $user = $userRepository->findOneByName('Sara');