简体   繁体   English

Symfony2-传入变量“ form”时不存在

[英]Symfony2 - Variable “form” does not exist when it's being passed in

I'm working on code to send email from a contact form and the form appears correctly until I submit the form then get the following error: 我正在研究从联系人表单发送电子邮件的代码,并且表单正确显示,直到我提交表单,然后出现以下错误:

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

Puzzled to what is causing this as I've dumped the 'form' variable in Twig and it's being passed in, but I'm guessing not during the redirect? 我在Twig中转储了'form'变量并将其传递时,对造成这种情况的原因感到困惑,但是我猜不是在重定向期间?

Controller 控制者

/**
 * @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()
    );
}

Twig 枝条

{% 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 %}

Form 形成

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

The error message seems pretty self-explanatory. 错误消息似乎很不言自明。 This snippet: 此代码段:

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

is rendering the view but not passing form into it. 正在渲染视图,但不将form传递给它。 The index.html.twig file tries to access form and throws an error because you haven't sent form to it. index.html.twig文件尝试访问form并抛出错误,因为尚未向其发送form I'm wondering why you would send an HTML form in an email... which leads me to think you are using the incorrect Twig file for your SwiftMailer function . 我想知道为什么您要通过电子邮件发送HTML表单...这使我认为您的SwiftMailer函数使用的Twig文件不正确

To fix the problem you either have to include form in the renderView function: 要解决此问题,您必须在renderView函数中包含form

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

or use the correct template that you're trying to send through the email (this solution seems more appropriate.) 或使用您尝试通过电子邮件发送的正确模板(此解决方案似乎更合适。)

One potential reason that you are receiving this error is that you are not actually passing the form to the view. 您收到此错误的一个潜在原因是您实际上没有将表单传递给视图。 Where you have: 您在哪里:

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

You need to do something like: 您需要执行以下操作:

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

There are a few other troubling aspects about your code. 关于代码,还有其他一些令人困扰的方面。 For instance, it would be a lot better to do something like: 例如,执行以下操作会更好:

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

Then in your mailing process, instead of doing things like: 然后在您的邮件发送过程中,不要执行以下操作:

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

You would do things like: 您将执行以下操作:

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

Another thing that I noticed is that in your controller, if the request method isn't POST you are not returning a valid Response object. 我注意到的另一件事是,在您的控制器中,如果请求方法不是POST,则不会返回有效的Response对象。 Anyway, hope some of that helps. 无论如何,希望其中的一些帮助。

Edit: As @sjagr points out, annotations take care of this. 编辑:正如@sjagr指出的那样,注释会解决这一问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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