如何在Symfony中获取表单类型的doctrine存储库?

时间:2016-05-26 15:06:27

标签: php symfony doctrine-orm doctrine

我正在尝试在表单类型类中使用Doctrine。

这是代码

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

我收到这样的错误:

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

无论如何都要称之为学说?

1 个答案:

答案 0 :(得分:0)

我对分享这个答案感到非常惭愧,但如果你绝望,你可以使用这样的东西。 请尽量避免使用此解决方案并找到更好的内容,不要有任何全局变量。 另请注意,您已将存储库var从$ userRepository更改为$ 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');