2

我想要 createForm 但 symfony 不加载我的顶级表单:

这是我的代码:

在我的 frontend.html.twig 中:

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

在 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””)

什么时候出问题?

谢谢

问候

4

1 回答 1

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);
于 2012-09-21T10:21:50.633 回答