Symfony2 - 联系 FormBuilder。树枝模板中不存在可变形式。一个网站页面

Symfony2 - contact FormBuilder. Variable form does not exist in twig template. One site page

当我尝试在我的 OneSitePage 网站上制作一个简单的联系表格时,我在 symfony2 FormBuilder 下坐了三个小时。我会注意到我主要是前端,但我需要通过 symfony2 通过 Swiftmailer 发送电子邮件。请不要问,为什么我使用 symfony :)

问题:我的主页上的渲染表单有问题,因为 Symfony 说,就像在主题中一样:

"Variable "表单“在 YodaHomeBundle::layout 中不存在。html.twig...” 它指向我使用树枝形式的行(附在下面的 TWIG 部分)

好的,这就是介绍。下面我介绍 PHP class 控制器和 ContactType class,下面我还附上了布局。html.twig 文件。

首先是控制器,我有两个操作,索引和联系。

namespace Yoda\HomeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Routing\Annotation\Route;
use Yoda\UserBundle\Entity\User;
use Yoda\HomeBundle\Form\ContactType;
use Symfony\Component\Form\FormInterface;


class HomeController extends Controller{

    /**
      * @Route("/home", name="homePage")
      * @Template()
      *
      */
    public function indexAction(){

        return $this->render('YodaHomeBundle::layout.html.twig');

    }

    public function contactAction(Request $request)
    {

        $form = $this->createForm(new ContactType());

        $adress = 'grzegorz.developer@gmail.com';

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

            if($form->isValid())
            {
                $message = \Swift_Message::newInstance()
                    ->setSubject($form->get('subject')->getData())
                    ->setFrom($form->get('email')->getData())
                    ->setTo($adress)
                    ->setBody(
                        $this->renderView('@YodaHome/mail/contact.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 mail has been send! Thank you, I will back to you, as soon as it\'s possible!');

                return $this->redirect($this->generateUrl('homePage'));

            }
        }

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

    }

}

now builder,在许多 tuts 上使用的简单生成器。

class ContactType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array(
            'attr' => array(
                'placeholder'   => 'What\'s your name?',
                'length'        => '.{2,}'
            )
        ))
        ->add('email', 'email', array(
            'attr' => array(
                'placeholder'   => 'So I can write back to you'
            )
        ))
        ->add('subject', 'text', array(
            'attr' => array(
                'placeholder'   => 'Subject of your message',
                'pattern'       => '.{5,}'
            )
        ))
        ->add('message', 'text', array(
            'attr' => array(
                'cols'          => '90',
                'row'           => '10',
                'placeholder'   => 'And ad your message to me...'
            )
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $collectionConstraint = new Collection(array(
            'name' => array(
                new NotBlank(array('message' => 'You forgot about the Name.')),
                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 'homePage';
    }

最后放置路由和 TWIG:

mail_create:
    path:     /homePage
    defaults: { _controller: "YodaHomeBundle:Home:contact" }
    requirements: { _method: post }

[...]
    <form action="{{ path('mail_create') }}" method="post">
                    {{ form_start(form) }}
                    {{ form_widget(form) }}
                    {{ form_end(form) }}
    </form>
[...]

求支持,到处都是不同联系方式的解决方案,我一个页面都有。欢迎大家多多指教,多多评论!

乌兰

这是因为您没有将在您的控制器中创建的表单对象传递给您的视图,因为您没有调用您的联系人控制器。

如果它是一页,请使用您的表单创建一个名为 contact.html.twig 的树枝视图,并在您要呈现表单的位置添加索引树枝模板:

{{ render(controller('YodaHomeBundle:Home:contact')) }}

这个 twig 方法将调用您的 indexControllercontactAction

您需要通过以下方式在布局树枝上呈现表单:

 public function indexAction(){
    $form = $this->createForm(new ContactType());
    return $this->render('YodaHomeBundle::layout.html.twig',array('form' => $form->createView());

}

或者你可以拆分布局,一个控制器是一个布局:

控制器:

class HomeController extends Controller{

/**
  * @Route("/home", name="homePage")
  * @Template()
  *
  */
public function indexAction(){

    return $this->render('YodaHomeBundle::layout.html.twig');

}

public function contactAction(Request $request)
{

    $form = $this->createForm(new ContactType());
    // do your code

    return array(
        'YodaHomeBundle::contactlayout.html.twig',
    array('form' => $form->createView());

}

}

对于 TWIG: layout.html.twig:

[..]
<div>{{ render(controller('YodaHomeBundle:Home:contact')) }}</div>
[..]

联系人layout.html.twig:

[..]
    <form action="{{ path('mail_create') }}" method="post">
                {{ form_start(form) }}
                {{ form_widget(form) }}
                {{ form_end(form) }}
    </form>
[..]