Reputation: 31910
I have a form I need to use on multiple pages:
Controller
$emailForm = $this->get('form.factory')->createNamedBuilder('form', 'email_form')
->add('email', 'email')
->add('subject', 'text')
->add('body', 'textarea')
->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST' && $request->request->has('email_form') ) {
$emailForm->bindRequest($request);
if ($emailForm->isValid()) {
// do stuff ...
$this->get('session')->setFlash('email_sent', "Woey, mail sent successfully!");
// Redirect on the same url to prevent double posts
return $this->redirect($this->generateUrl($this->getRequest()->attributes->get('_route')));
}
}
return $this->render('Bundle:Form:index.html.twig', array('email_form' => $emailForm->createView()));
Template
{% if app.session.getFlash('email_sent') %}
<p>{{ app.session.getFlash('email_sent') }}</p>
{% endif %}
<form action="{{ path(app.request.attributes.get('_route')) }}" method="post" {{ form_enctype(email_form) }}>
{{ form_widget(email_form) }}
<p><input type="submit" class="submit" value="Send" /></p>
</form>
It's really just standard Symfony2 form, almost like from tutorial.
I can't figure how can I efficiently use it on multiple pages (in multiple controller actions) without repeating myself (too much). So far I tried:
So, what's the common approach to such forms?
Edit:
I'm looking for a no script solution.
Upvotes: 4
Views: 1703
Reputation: 31910
I ended up using embedded controller on every page I needed, posting to different URL and saving cookie with referrer. Then I validate form, save cookie with results, redirect back to referrer and render results (errors, thank you message...). This seems to be the best option when you are dealing with scenarios where you have to think about disabled Javascript. You can easily disable creating of redundant cookies / flash sessions using simple conditions for cases when user is posting using AJAX.
Upvotes: 2
Reputation: 17282
You should submit the data via an ajax post.
In the controller do your thing :p Then render the form in the twig template, without extending layouts. (like it would be currently)
Then in any view you just replace the result: $('#formDiv').html(htmlReceivedBack);
I find it the easiest to just replace the whole html div again with the new rendered html; most likely you will show a success message or some form errors.
This way the user don't have to change pages just to send a message/feedback.
Upvotes: 1
Reputation: 197682
The Symfony2 Forms tutorial addresses your scenario as well, see the Creating Form ClassesDocs Section in which "you'll learn how to build your form in a standalone class, which is recommended as your form becomes reusable" (Ibid.).
Upvotes: 1