dongtang8678 2014-01-03 10:24
浏览 78
已采纳

Symfony2表单为什么我的表单返回警告:json_encode():检测到递归?

I have to entities, Applications and Votes.

The idea is to relate many to one. So Applications have many Votes and one Vote is for one Application.

In my entities class I have settings like this:

Application Entity Class:

\/**
\* @ORM\OneToMany(targetEntity="Vote", mappedBy="application")
\*/
\private $votes;

Vote Entity Class:

\/**
\* @ORM\ManyToOne(targetEntity="Application", inversedBy="votes")
\* @ORM\JoinColumn(referencedColumnName="id")
\*/
\private $application;

I think this relation is set up well or am I mistaken ?

Next thing is that I have a form builder class for only one field:

$builder->add('rate')
    ->add('save', 'submit');

The Votes entity has fields: (id, username, rate, createdAt, updatedAt, application)

and in my controller I'm doing something like this:

    $vote = new Vote();
    $form = $this->createForm(new VoteType(), $vote);

    $form->handleRequest($this->getRequest());

    if ($form->isValid()) {
        $vote->setUserName($tenant->getUsername());
        $vote->setApplication($app);
        $em->persist($vote);
        $em->flush();

        $this->get('session')->getFlashBag()->add('success', 'Oceniono aplikację.');

        return $this->redirect($this->generateUrl('applications_main'));
    }

    return array( 'form' => $form->createView(), );

and it isn't working, it returns me error:

ContextErrorException: Warning: json_encode(): recursion detected in E:\wamp\www\project\vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\JsonResponse.php line 92

stack trace (plain text): http://pastebin.com/bSQTDJQY

  • 写回答

1条回答 默认 最新

  • doudeng8691 2014-01-03 11:08
    关注

    Entities are prone to recursive issues, if you var_dump or print_r an entitiy, it will hang.

    One of the best serialization tools that is capable of turning an entity into a hierarchal non-recursive tree is: https://github.com/schmittjoh/JMSSerializerBundle

    It is used with FOSRestBundle as part of its transparent acceptable response handing.

    You are having a similar issue to this: Avoiding recursion with Doctrine entities and JMSserializer

    Check out the solution, and try using JMSSerializer.

    Edit: Other likely cause:

    When you return the array you are returning the form contained within that array. Your event listener is trying to serialize this as json, this is both a cause of issues as well as being relatively pointless unless the form is being used to provide an augmented data template.

    Either way, a form cannot be serialized so simply, did you even mean to do that?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大