简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM