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:
- putting the logic into Base controller, which is parent for every controller where I want to have this form. There were 2 problems with this approach:
- I couldn’t figure how to redirect properly to the same page
- I had to call method from parent in every action, which isn’t really a problem, but I guess there has to be some more elegant way
- rendering controller using embedded controllers in twig. However, I couldn’t figure how to redirect properly.
So, what’s the common approach to such forms?
Edit:
I’m looking for a no script solution.
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.