I am building a web application that involves forms. The framework being used is symfony2. I would like to have everything working for users without javascript, and then progres
You can return a response like usual and decide on the view if you want to do a partial render or render the whole page by extending different twig layouts.
In your controller:
if ($form->isValid()) {
// perform some action, such as saving the task to the database
$this->get('session')->setFlash('notice', 'Success!');
return $this->render('success.html.twig');
} else {
$this->get('session')->setFlash('notice', 'Please correct the errors below');
}
And in your views:
{# new.html.twig #}
{% extends app.request.isXmlHttpRequest ? 'ajax.html.twig' : 'layout.html.twig' %}
{% block content %}
{% if app.session.hasFlash('notice') %}
{{ app.session.flash('notice') }}
{% endif %}
{% endblock %}
{# success.html.twig #}
{% extends app.request.isXmlHttpRequest ? 'ajax.html.twig' : 'layout.html.twig' %}
{% block content %}
{% if app.session.hasFlash('notice') %}
{{ app.session.flash('notice') }}
{% endif %}
{% endblock %}
{# ajax.html.twig #}
{% block content %}{% endblock %}
{# layout.html.twig #}
normal page content
{% block content %}{% endblock %}
(You might want to put the flash messages part in a macro or an include...)
Now simply render the return from the ajax request into the tag you want to place it:
$.ajax({
type: "POST",
url: "tasks/new",
data: {task: foo, dueDate: bar},
}).done(function( msg ) {
$('#content').html(msg);
});