Symfony2 - 用于 AJAX 调用的实体存储库 JSON 编码

问题描述 投票:0回答:2

我正在尝试构建一个具有 AJAX 自动完成功能的动态文本字段。

我在控制器中定义了一个用于 AJAX 调用的方法。

public function cityAction(Request $request)
{
    $repository = $this->getDoctrine()
        ->getRepository('UserCityBundle:District');

    $items = $repository->findAll();

// $format = $request->getRequestFormat();
// \Doctrine\Common\Util\Debug::dump($items);

    return $this->render('CommonAjaxBundle:Default:index.html.twig', array('data' => array(
        'success' => true,
        'root' => 'district',
        'count' => sizeof($items),
        'rows' => $items
    )));
}

进入树枝文件:

{{ data | json_encode | raw }}

我从如何在 Symfony2 中进行 ajax 调用的示例中获取了这一点。 它应该打印我的区实体存储库的 json 编码,但我得到了这个结果:

{"success":true,"root":"district","count":6,"rows":[{},{},{},{},{},{}]} 

为什么它不打印括号之间的字段?

php jquery json ajax symfony
2个回答
3
投票

您可以通过序列化器组件序列化您的实体(请参阅http://symfony.com/doc/current/components/serializer.html)。

要序列化您的实体,您可以使用上面链接中描述的 GetSetMethodNormalizer 类,也可以创建一个规范化器并将其声明为在捆绑包的服务定义文件(Resource/ config/service.yml(如果您使用 yaml 配置)。 parameters: common_ajax_bundle.district.normalizer.class: Full\Path\To\Your\normalizer\Class common_ajax_bundle.district.normalizer: class: '%common_ajax_bundle.district.normalizer.class%' tags: - { name: serializer.normalizer }

规范化器类可以扩展 
Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer

类。通过方法

$this->setIgnoredAttributes(array(/* the fields to ignore */))
将所有要忽略的字段放入构造函数中,或者您可以从头开始创建它,它只需要实现
Symfony\Component\Serializer\Normalizer\NormalizerInterface
接口即可。

然后在你的控制器中:

public function cityAction(Request $request) { $repository = $this->getDoctrine() ->getRepository('UserCityBundle:District'); $items = $repository->findAll(); $serializer = $this->container->get('serializer'); // serialize all of your entities $serializedCities = array(); foreach ($items as $city) { $serializedCities[] = $serializer->normalize($city, 'json'); } return new JsonResponse(array( 'success' => true, 'root' => 'district', 'count' => sizeof($items), 'rows' => $serializedCities )); }



1
投票

use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; use Symfony\Component\Serializer\Encoder\JsonEncoder; $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder())); $json = $serializer->serialize($entity, 'json');

就我而言,我构建了一个 twig 函数,以便返回有限数量的数据(也能够重命名关键属性):

namespace Company\EgBundle\Services; class TwigExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('encode_entity', array($this, 'encodeEntity')), ); } public function encodeEntity($entity, $filter = null) { $data = []; $methods = get_class_methods($entity); if ($filter) { $methods = array_intersect($methods, array_keys($filter)); } foreach ($methods as $method) { if (strpos($method, 'get') === 0) { $value = $entity; while(is_object($value)) { $value = $value->$method(); } $key = $filter ? $filter[$method] : substr($method, 3); $data[$key] = $value; } } return json_encode($data); } }

要在模板中使用此功能,请执行以下操作:

{{ row|encode_entity({'getProductName': 'name', 'getIdIsoCry': 'currency'}) }}

© www.soinside.com 2019 - 2024. All rights reserved.