Symfony2 - 通过Ajax发送其他数据和表单数据会导致IsValid()返回false

时间:2013-12-10 13:36:55

标签: php ajax forms validation symfony

我正在尝试将其他数据和提交的表单一起发送到Symfony2内的控制器。

当我尝试这样的时候:

$("#submit_btn").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: post_url,
            data: form.serialize()
        });
    });

我看到我获得了一个成功的POST请求,然后在控制器操作中按预期重定向,如果IsValid()返回true。

但是当我尝试使用以下形式发送其他数据时:

$("#submit_btn").on("click", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: post_url,
            data: { form: form.serialize(), otherdata: "test" }
        });
    });

我没有得到重定向302响应。相反,当200方法返回false时,我只得到一个IsValid()响应。我在这里的问题是如何不仅发送表单,还发送其他数据?

这是我的控制器动作:

public function postOverviewAction(Request $request, $id)
    {
        $overview = $this->get("doctrine_mongodb")->getRepository("GbrBEBundle:Overview")->findOneById($id);
        $overview_photos = $this->get("doctrine_mongodb")->getRepository("GbrBEBundle:OverviewPhoto")->findAll();
        $form = $this->createForm(new OverviewType(), $overview);
        $form->handleRequest($request);

        $height = $form->get("coordinate_height")->getData();
        $width = $form->get("coordinate_width")->getData();
        $x = $form->get("coordinate_x")->getData();
        $y = $form->get("coordinate_y")->getData();

        if($form->isValid())
        {
            $overview->setCropCoordinates(array('height' => $height, 'width' => $width, 'x' => $x, 'y' => $y));
            $dm = $this->get("doctrine_mongodb")->getManager();
            $dm->persist($overview);
            $dm->flush();
            return $this->redirect($this->generateUrl("gbr_be_get_overview"));
        }
        return $this->render("GbrBEBundle:Default:overview.html.twig", array(
            "form" => $form->createView(),
            "overview" => $overview,
            "overview_photos" => $overview_photos,
        ));
    }

2 个答案:

答案 0 :(得分:1)

您可以在表单中添加未映射的字段:

How do I add an unbound field to a form in Symfony which is otherwise bound to an entity?

设置为text类型应该是最通用的。

您还可以创建collection字段作为未映射字段,并为其指定text类型。这将允许您在接收端有多个附加文本数据。

http://symfony.com/doc/current/reference/forms/types/collection.html

答案 1 :(得分:0)

可能会尝试改变:

 data: { form: form.serialize(), otherdata: "test" }

通过      data:form.serialize()+'& otherdata = test',

我认为是因为.serialize()返回一个字符串。