In symfony 2, one can embed a controller in a template. For example, I might have a template for a blog post, but I can also embed a controller to a poll or a list of top articles in the side-bar of the template.
I am interested in embedding a controller that provides a poll. To do so, I have created a controller:
public function poll(Request $request)
{
$task = new Poll();
$form = $this->createFormBuilder($task)
->add('radio', 'one')
->add('radio', 'two')
->add('radio', 'three')
->getForm();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
//save and show how many people voted for each option
}
}
return $this->render('PollBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
I can then embed this as a side bar item in my template:
<div id="sidebar">
{% render "PollBundle:Poll:poll" %}
</div>
The problem now is this:
If I set the form action to be ""
, then if the poll was submitted, the request would go through the main controller which embeds the Poll controller. I can then use a hidden field to check if the poll was submitted using the poll form, then update the database and render the result. This then gets returned to the template of the main controller and all is good.
I would now like to use some AJAX to streamline the form submission for those who have javascript enabled. How can I go about doing this? Since the form action is set to ""
, the request would go through the main controller, render the template which then calls the Poll controller. But I would like to just return an AJAX response containing the votes casted for each item. In anycase, having to go through the main controller just to populate a poll using an AJAX request seesm to be quite wasteful too.
How should I go about doing this?
You can point the form to its own action that handles the post and, if it's being requested through ajax then return the results or, if it's reached through a normal request, redirect to the
HTTP_REFERER
($this->get('request')->server->get('HTTP_REFERER')
).If you don't want to rely on the referer, you could also store the current URI in a session variable when rendering the poll (in the pollAction you've described above).