使用ajax在Symfony 3中提交多个表单?

时间:2018-05-27 20:39:21

标签: javascript jquery ajax symfony

我正在尝试使用Jquery创建一个动态的两步表单,在“步骤1”中,我想提交表单数据而不刷新我的页面,以便我可以隐藏包含我的表单的html分区并显示其他用Jquery代表我的第2步。

问题是我在控制器操作中使用了一组表单,如下所示:

public function indexAction(Request $request)
{

$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('ATPlatformBundle:NoteDeFrais');


$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class,array(
'entry_type'   => NoteDeFraisType::class,
'label'        => false,
'allow_add'    => true,
'allow_delete' => true,
))
->getForm(); 

我正在从这样提交表单数据:

if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()
&& isset($_POST['next_button'])) {

$notesDeFrais = $form['ndf']->getData();

foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$em->persist($ndf);
}

$em->flush();

}

elseif (isset($_POST['validate_button'])) {

foreach ($listNdf as $ndf) {
$ndf->setSubmitted(true);
}
$em->flush();
}

所以我想知道的是如何通过ajax请求发送我的数据以及如何从我的行动中获取它们。到目前为止,我试图这样做,但它(逻辑上)不起作用。

$("div#bloc_validation").css("display", "none");

$("#next_button").click(function(){

$(".form_ndf").each(function(){

$.post("{{ path('platform_homepage') }}",
{ndf: $(this).serialize()}, //My issue is here
function(){
alert('SUCCESS!');
}
);
});

$("div#form_bloc ").css("display", "none");
$("div#bloc_validation").css("display", "block");
});

你有什么想法吗?提前致谢

1 个答案:

答案 0 :(得分:0)

最基本的方法是:

在twig文件中添加javascripts块,其内容如下所示。 更改表单名称中.ready()函数内第一行的appbundle_blog 。 (检查你的HTML以找到它。)

{% extends 'base.html.twig' %}

{% block body %}
    {{ form_start(edit_form) }}
        {{ form_widget(edit_form) }}
        <input type="submit" value="Save Changes" />
    {{ form_end(edit_form) }}
{% endblock %}

{% block javascripts %}
    <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous">
    </script>
    <script>
        $(document).ready( function() {
          var form = $('form[name=appbundle_blog]');

          form.submit( function(e) {
            e.preventDefault();
            $.ajax( {
              type: "POST",
              url: form.attr( 'action' ),
              data: form.serialize(),
              success: function( response ) {
                console.log( response );
              }
            });
          });
        });
    </script>
{% endblock %}

如果表单已提交,则必须回答AJAX请求。因此,您可以渲染另一个模板..

/**
 * Displays a form to edit an existing blog entity.
 *
 * @Route("/{id}/edit", name="blog_edit")
 * @Method({"GET", "POST"})
 */
public function editAction(Request $request, Blog $blog)
{
    $editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        /* render some new content */
        return $this->render('blog/ajax.html.twig', array(
            'blog' => $blog,
        ));
    }

    return $this->render('blog/edit.html.twig', array(
        'blog' => $blog,
        'edit_form' => $editForm->createView(),
    ));

或者用JSON回答:

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Displays a form to edit an existing blog entity.
 *
 * @Route("/{id}/edit", name="blog_edit")
 * @Method({"GET", "POST"})
 */
public function editAction(Request $request, Blog $blog)
{
    $editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return new JsonResponse(array(
            'status' => 'success',
            // ...
        ));
    }

    return $this->render('blog/edit.html.twig', array(
        'blog' => $blog,
        'edit_form' => $editForm->createView(),
    ));
}

如果您愿意,您甚至可以测试请求是否是AJAX请求:

if($request->isXmlHttpRequest()) {
    // yes it is AJAX
}