Jooni Joon Jooni Joon - 6 months ago 122
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');

$builder
->setAction($options['data']['url'])
->setMethod('GET')
->add('user', 'text', array(
'user.id' => $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

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

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