Jooni Joon Jooni Joon - 1 year ago 285
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?

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download