Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle forms that are used on multiple pages?
    text
    copied!<p>I have a form I need to use on multiple pages:</p> <p><strong>Controller</strong></p> <pre><code>$emailForm = $this-&gt;get('form.factory')-&gt;createNamedBuilder('form', 'email_form') -&gt;add('email', 'email') -&gt;add('subject', 'text') -&gt;add('body', 'textarea') -&gt;getForm(); $request = $this-&gt;get('request'); if ($request-&gt;getMethod() == 'POST' &amp;&amp; $request-&gt;request-&gt;has('email_form') ) { $emailForm-&gt;bindRequest($request); if ($emailForm-&gt;isValid()) { // do stuff ... $this-&gt;get('session')-&gt;setFlash('email_sent', "Woey, mail sent successfully!"); // Redirect on the same url to prevent double posts return $this-&gt;redirect($this-&gt;generateUrl($this-&gt;getRequest()-&gt;attributes-&gt;get('_route'))); } } return $this-&gt;render('Bundle:Form:index.html.twig', array('email_form' =&gt; $emailForm-&gt;createView())); </code></pre> <p><strong>Template</strong></p> <pre><code>{% if app.session.getFlash('email_sent') %} &lt;p&gt;{{ app.session.getFlash('email_sent') }}&lt;/p&gt; {% endif %} &lt;form action="{{ path(app.request.attributes.get('_route')) }}" method="post" {{ form_enctype(email_form) }}&gt; {{ form_widget(email_form) }} &lt;p&gt;&lt;input type="submit" class="submit" value="Send" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>It's really just standard Symfony2 form, almost like from tutorial.</p> <p>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:</p> <ul> <li>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: <ul> <li>I couldn't figure how to redirect properly to the same page</li> <li>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</li> </ul></li> <li>rendering controller using <a href="http://symfony.com/doc/current/book/templating.html#embedding-controllers" rel="nofollow noreferrer">embedded controllers</a> in twig. However, I couldn't figure <a href="https://stackoverflow.com/questions/6984429/redirect-from-embedded-controller">how to redirect properly</a>.</li> </ul> <p>So, what's the common approach to such forms?</p> <p><strong>Edit:</strong></p> <p>I'm looking for a no script solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload