你的问题激发了我的好奇心,我尝试了一些不同的东西。想出了一种有趣的方法来使用单个表单和单个操作createFormBuilder
在控制器中使用它来处理它,但我找不到使用createForm
with a的方法,FormType
因为在调用$form = $this->createForm(new NewsletterSignupType());
.
感觉有点hacky,但它就是在这里,希望如果没有别的,它会给你一些想法。
class DemoController extends Controller
{
/**
* @Route("/", name="newsletter_signup")
* @Template()
*/
public function newsletterSignupAction(Request $request)
{
$form = $this->getNewsletterSignupForm();
$form->handleRequest($request);
if ($form->isValid()) {
$newButton = $form->get('new');
$editButton = $form->get('edit');
$createButton = $form->get('create');
if ($newButton->isClicked()) {
$form = $this->getNewsletterSignupForm($form->getData(), true);
}
if ($editButton->isClicked()) {
/**
* We don't have to do anything here because we are just
* returning the original form with the submitted data attached
*/
}
if ($createButton->isClicked()) {
// User verified data and clicked "Create"
$response = 'Thank you for signing up!';
return new Response($response);
}
}
return array(
'form' => $form->createView()
);
}
/**
* Handle creating the form and setting fields / buttons and data
*/
protected function getNewsletterSignupForm($data = null, $previewMode = false)
{
$actionUrl = $this->generateUrl('newsletter_signup');
$formBuilder = $this->createFormBuilder($data);
$fieldAttributes = [];
$newButtonAttributes = [];
$previewButtonAttributes = [];
if ($previewMode) {
$fieldAttributes['read_only'] = true;
$newButtonAttributes['attr'] = ['hidden' => true];
} else {
$previewButtonAttributes['attr'] = ['hidden' => true];
}
$formBuilder->add('name', 'text', $fieldAttributes)
->add('email_address', 'email', $fieldAttributes)
->add('new', 'submit', $newButtonAttributes)
->add('edit', 'submit', $previewButtonAttributes)
->add('create', 'submit', $previewButtonAttributes);
$formBuilder->setAction($actionUrl);
$form = $formBuilder->getForm();
return $form;
}
}
查看代码:
{# Acme:DemoBundle:newsletterSignup.html.twig #}
{% extends 'AcmeDemoBundle::layout.html.twig' %}
{% block content %}
{{ form(form) }}
{% endblock content %}