繁体   English   中英

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

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

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

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

“可变的“表单”在YodaHomeBundle :: layout.html.twig ...中不存在” ,它指向我正在使用树枝表单的行(附在TWIG部分中)

好的,那是介绍。 在下面,我展示控制器的PHP类和ContactType类,也在下面,我附加了layout.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()
        );

    }

}

现在的构建器,用于许多tut的简单构建器。

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>
[...]

请寻求支持,到处都是用于不同联系方式的解决方案,我将所有内容都放在一页上。 欢迎所有提示,请发表评论!

乌兰

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

 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>
[..]

contactlayout.html.twig:

[..]
    <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')) }}

这个树枝方法将调用您的indexControllercontactAction

暂无
暂无

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

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