Ajax form submission in symfony2 with graceful degradation for users without javascript

后端 未结 3 1359
悲&欢浪女
悲&欢浪女 2021-01-30 04:57

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 05:31

    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 %}
    {{ form_widget('form') }}
    {% 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);
    });
    

提交回复
热议问题