Symfony2在createForm时不加载Type

时间:2012-09-21 10:18:53

标签: symfony symfony-2.1

我想要createForm,但symfony没有加载我的顶级表单:

这是我的代码:

在我的frontend.html.twig中:

{% render "NewsletterBundle:Default:form" %}

in NewsletterBundle / Form / NewsletterUserType.php:

<?php

namespace LoPati\NewsletterBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Tag;

/**
 * @Service("lopati.form.newsletter_user")
 * @Tag("form.type", attributes = { "alias" = "mp_newsletter_user" })
 */
class NewsletterUserType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('email')
        ;
    }


    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'LoPati\NewsletterBundle\Entity\NewsletterUser'
        ));
    }

    public function getName()
    {
        return 'mp_newsletter_user';
    }

}

在NewsletterBundle / Controller / DefaultController.php中:

<?php

namespace LoPati\NewsletterBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use LoPati\NewsletterBundle\Entity\NewsletterUser;

class DefaultController extends Controller 
{

    /**
     * @Template()
     */
    public function formAction(Request $request)
    {
        $newsletterUser = new NewsletterUser();

       $form = $this->createForm('mp_newsletter_user', $newsletterUser);

        return array('form' => $form->createView());
    }

}

在NewsletterBundle / Resources / views / Default / form.html.twig

<form action="" method="post" class="newsletter">
    {{ form_widget(form.email) }}
    {{ form_widget(form._token) }}    
    <button type="submit">newsletter</button>
</form>

这是错误:

  

在渲染模板期间抛出了异常   (“无法加载类型”mp_newsletter_user“”)

什么时候出现问题?

谢谢

此致

1 个答案:

答案 0 :(得分:4)

您已将表单定义为服务,因此,请将创建表单更改为:

 // $form = $this->createForm('mp_newsletter_user', $newsletterUser);
 $form = $this->createForm($this->get('mp_newsletter_user'), $newsletterUser); // you need use $this->get to get a service

这也应该有效:

 $this->createForm(new \LoPati\NewsletterBundle\Form\NewsletterUserType(), $newsletterUser);