Symfony2 - 变量"形式"当它被传入时不存在

时间:2014-08-27 01:13:13

标签: forms email symfony

我正在处理从联系表单发送电子邮件的代码,表单正确显示,直到我提交表单然后出现以下错误:

Variable "form" does not exist in AcmeEmailBundle:Default:index.html.twig at line 14

因为我在Twig中转储了'form'变量并且正在传入,但是我猜测不是在重定向期间?

控制器

/**
 * @Route("/", name="contact")
 * @Template("AcmeEmailBundle:Default:index.html.twig")
 */
public function contactAction(Request $request)
{
    $form = $this->createForm(new ContactType());

    if ($request->isMethod('POST')) {
        $form->submit($request);

        if ($form->isValid()) {
            $message = \Swift_Message::newInstance()
                ->setSubject($form->get('subject')->getData())
                ->setFrom($form->get('email')->getData())
                ->setTo('example@gmail.com')
                ->setBody(
                    $this->renderView(
                        'AcmeEmailBundle:Default:index.html.twig',
                        array(
                            'ip' => $request->getClientIp(),
                            'name' => $form->get('name')->getData(),
                            'message' => $form->get('message')->getData()
                        )
                    )
                );

            $this->get('mailer')->send($message);

            $request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!');

            return $this->redirect($this->generateUrl('contact'));
        }
    }

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

枝条

{% block body %}

{% for label, flashes in app.session.flashbag.all %}
    {% for flash in flashes %}
        <div class="alert alert-{{ label }}">
            {{ flash }}
        </div>
    {% endfor %}
{% endfor %}

<form action="{{ path('contact') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    <button type="submit">Send</button>
</form>

{% endblock %}

表格

class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('name', 'text', array(
    'attr' => array(
        'placeholder' => 'What\'s your name?',
        'pattern'     => '.{2,}' //minlength
    )
))
    ->add('email', 'email', array(
        'attr' => array(
            'placeholder' => 'So I can get back to you.'
        )
    ))
    ->add('subject', 'text', array(
        'attr' => array(
            'placeholder' => 'The subject of your message.',
            'pattern'     => '.{3,}' //minlength
        )
    ))
    ->add('message', 'textarea', array(
        'attr' => array(
            'cols' => 90,
            'rows' => 10,
            'placeholder' => 'And your message to me...'
        )
    ));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $collectionConstraint = new Collection(array(
        'name' => array(
            new NotBlank(array('message' => 'Name should not be blank.')),
            new Length(array('min' => 2))
        ),
        'email' => array(
            new NotBlank(array('message' => 'Email should not be blank.')),
            new Email(array('message' => 'Invalid email address.'))
        ),
        'subject' => array(
            new NotBlank(array('message' => 'Subject should not be blank.')),
            new Length(array('min' => 3))
        ),
        'message' => array(
            new NotBlank(array('message' => 'Message should not be blank.')),
            new Length(array('min' => 5))
        )
    ));

    $resolver->setDefaults(array(
        'constraints' => $collectionConstraint
    ));
}

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

2 个答案:

答案 0 :(得分:3)

错误消息似乎很明显。这个片段:

// ...
                $this->renderView(
                    'AcmeEmailBundle:Default:index.html.twig',
                    array(
                        'ip' => $request->getClientIp(),
                        'name' => $form->get('name')->getData(),
                        'message' => $form->get('message')->getData()
                    )
// ...

正在渲染视图,但没有将form传递给它。 index.html.twig文件尝试访问form并引发错误,因为您尚未向其发送form。我想知道你为什么要在电子邮件中发送HTML表单......这让我想到你正在使用SwiftMailer函数的错误Twig文件

要解决此问题,您必须在form函数中加入renderView

// ...
                $this->renderView(
                    'AcmeEmailBundle:Default:index.html.twig',
                    array(
                        'ip' => $request->getClientIp(),
                        'name' => $form->get('name')->getData(),
                        'message' => $form->get('message')->getData(),
                        'form' => $form->createView(),
                    )
// ...

或使用您尝试通过电子邮件发送的正确模板(此解决方案似乎更合适。)

答案 1 :(得分:0)

您收到此错误的一个可能原因是您实际上没有将表单传递给视图。你在哪里:

->setBody(
$this->renderView(
'AcmeEmailBundle:Default:index.html.twig', array(
    'ip' => $request->getClientIp(),
    'name' => $form->get('name')->getData(),
    'message' => $form->get('message')->getData()
))

您需要执行以下操作:

->setBody(
$this->renderView(
'AcmeEmailBundle:Default:index.html.twig', array(
    'ip' => $request->getClientIp(),
    'form' => $form->createView()
))

您的代码还有其他一些令人不安的方面。例如,做类似的事情要好得多:

$contact = new Contact(); // Where contact is some kind of Entity
$form = $this->createForm(new ContactType(), $contact);
$form->handleRequest($request);

然后在您的邮寄过程中,而不是做以下事情:

->setSubject($form->get('subject')->getData())
->setFrom($form->get('email')->getData())

你可以这样做:

->setSubject($contact->getSubject())
->setFrom($contact->getEmail())

我注意到的另一件事是,在你的控制器中,如果请求方法不是POST,你就不会返回一个有效的Response对象。无论如何,希望其中一些有帮助。

编辑:正如@sjagr指出的那样,注释可以解决这个问题。