【问题标题】:Symfony 2 - same form on different pagesSymfony 2 - 不同页面上的相同表单
【发布时间】:2013-03-01 19:51:31
【问题描述】:

我的网站上有许多页面上呈现的联系表单,我需要在许多不同的控制器中处理此表单。如何在所有这些控制器中处理这种形式? 我不想定义特殊的路由和控制器来处理这个表单,我需要在它呈现的所有页面中处理它。

现在我正在调用控制器操作女巫以这种方式呈现我的表单:

在控制器中:

    $profileAskFormResponse = $this->forward('MyBundle:Profile:profileAskForm', array(
                'user' => $user,
            ));          
    if ($profileAskFormResponse->isRedirection())
                return $profileAskFormResponse;

    return $this->render(MyBundle:Single:index.html.twig', array(
                'myStuff' => $myStuff,
                'profileAskForm' => $profileAskFormResponse,
   ));

在树枝上:

{{ profileAskForm.content|raw }}

我在每个需要处理我的联系表的控制器中都使用此代码。有没有更简单的方法来做到这一点? 我的第一个想法是在 twig 中做这种事情:

{% render 'MyBundle:Profile:profileAskForm' with {request: app.request, user: user} %}

但我无法在表单发送后从那里重定向。关键是,是否有一种简单快捷的调用方式(例如

from twig) 像我的联系表单这样的组件,该组件不仅呈现一些东西,而且有一些

其中的应用程序逻辑。我会很高兴将这种组件用作砖女巫,我可以轻松地放在任何地方。

【问题讨论】:

  • 显示您现在如何调用表单。

标签: php symfony twig


【解决方案1】:

一种可能性是创建一个像Contact.php 这样的类,它将所有字段都作为类成员。然后,您可以非常轻松地向每个字段添加断言:

/**
  * @Assert\NotBlank(message="Please fill in your e-mail at least")
  * @Assert\Email(checkMX = true)
  */
protected $email;

你可以为这个类创建一个名为ContactType.php的表单类型并在其中使用FormBuilder

$builder->add('email', 'email', array('label' => 'E-mail'));

然后,您可以在所有控制器中重复使用该表单。您甚至可以使用处理所有外发电子邮件的电子邮件类对其进行扩展,然后将有效的联系表单注入其中:

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

if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if ($form->isValid()) {
        // now you can easily inject the class to the one that handles e-mail traffic for example
        $email = new Email();
        $email->sendContactForm($contact);
    }
}

您可以在Symfony2 Cookbook: Forms 中深入了解它。

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2015-03-02
    • 2016-03-26
    • 2018-06-09
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多