2

我正在修改网页中的实体(Symfony 没有什么不寻常的:))。我目前有一个应该修改的实体。我使用Jeditable进行该版本,而不是在版本之后立即修改实体,而是将修改后的元素存储在 json 中,当用户确认他的修改时(通过模态对话框确认操作),我将该 JSON 发送到我的控制器。

那就是事情变得更糟的时候^^

我检查了我的 json 数组是否包含正确的信息。但是当我在控制器中拦截请求时,它似乎不包含我想要的内容。这是我的控制器:

public function postorganisationAction(){
    $modifFields = array();
    $content = $this->get("request")->getContent();
    $this->get('logger')->info('request123456 ');
    if (!empty($content))
    {
        $modifFields = json_decode($content, true);
        $repository = $this->getDoctrine()
               ->getEntityManager()
               ->getRepository('MyBundle:Organisation');
        $organisation = $repository->findById($modifFields["id"]);
        $organisation->setFromArray($modifFields);

        $em = $this->getDoctrine()->getEntityManager();

        $em->persist($organisation);

        $em->flush();
    }

} 

setFromArray 函数获取一个包含元素的数组,例如"name" => "newname".

当我尝试记录请求、内容或$modifFields["id"](如我所说,我检查 JSON 中的 id 在 jquery 中是否正确)时,日志不会出现。

有人知道我做错了什么吗?

编辑:

经过一些修改(感谢 ManseUK),我能够:
- 让 jQuery 函数发送 JSON 字符串而不是数组(JSON.stringify(oModifFields);
- 解决问题: 我有一个转换错误$organisation,然后我变成了一个对象所需类型

就是这样^^

4

1 回答 1

0

Symfony2 有一些有用的类用于序列化和反序列化实体。

这是如何进行的:

  1. 定义一种将实体规范化为数组的方法,数组的每一对键/值都将是 json 字符串中的键/值;
  2. 导入一个序列化程序,它将您的数组(规范化的实体)转换为 json 字符串、XML 文档或您想要的任何内容。

对于第一个操作(规范化你的实体),Symfony2 内置了两种可能性:

  • 在你的实体上实现 Symfony\Component\Serializer\Normalizer\NormalizableInterface。您将必须填写两种方法,它们会将您希望在 json 中看到的属性规范化或非规范化到数组;
  • 创建你自己的 Normalizer 类,它将实现 Symfony\Component\Serializer\Normalizer\NormalizerInterface

在控制器(或您将定义的服务中)中,您将执行以下操作来对您的实体进行编码:

$serializer = new Symfony\Component\Serializer\Serializer(
       array(
          new Symfony\Component\Serializer\Normalizer\CustomNormalizer(), //if you implement NormalizableInterface
          new YourOwnCustomNormalizer() //if you created your own custom normalizers
       ), 
       array(
          'json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()
       )
    );
$json = $serializer->serialize($yourEntity, 'json');
return new Response($json);

并从 json 字符串中检索实体:

$jsonString = $content = $this->get("request")->get('yourString'); //please, check how you retrieve data from your request
$serializer = new Symfony\Component\Serializer\Serializer(
       array(
          new Symfony\Component\Serializer\Normalizer\CustomNormalizer(), //if you implement NormalizableInterface
          new YourOwnCustomNormalizer() //if you created your own custom normalizers
       ), 
       array(
          'json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()
       )
    );
$entity = $serializer->deserialize($jsonString, '\namespace\to\your\entity', 'json');
于 2012-08-13T10:22:44.970 回答