Symfony2 - JMS Serializer - Exclude entity if getDeleted() is not null

大兔子大兔子 提交于 2020-05-16 05:10:29

问题


I have nested OneToMany relationships. A form has question sections which have question groups that have questions which have possible answers.

What I need to achieve is, to ignore those sections or groups or questions or possible answers that are deleted (virtually using $deleted param)

Serializing without exclusion or by just excluding property (with expression) works fine.

But @JMS\Exclude(if="expression..") on class (not property) is ignored.

use JMS\Serializer\Annotation as JMS;

/**
 * @ORM\Entity
 * @ORM\Table(name="entity_question_section")
 * @JMS\Exclude(if="object.getDeleted() !== null")
 */
class QuestionSection
{
.......
}

The Exclude annotation is allowed to use on class "@Target({"PROPERTY", "CLASS", "METHOD", "ANNOTATION"})" but it does not work.

Does not matter what kind of expression i use, it will exclude all fields inside QuestionSection entity and returns empty object for each QuestionSection.

How I serialize

$serializer = $this->get('jms_serializer');
$serialized = $serializer->serialize($form, "json");
$response = new JsonResponse();
$response->setContent($serialized);

If I will need to do it by doing nested loops to build json response it will be probably very bad solution.

I have googled few hours to get this done, i have also tried JLM\SerializerExpressionBundle\JLMSerializerExpressionBundle() but it only supports to be defined on property and only exclude property.

I have also tried expression using service (if="service('general').isDeleted(object)")

Can anyone give me the right direction to solve this?

Thank you


回答1:


Thanks to @Rufinus i have used http://symfony.com/doc/current/bundles/StofDoctrineExtensionsBundle/index.html which solved my problem. Now "deleted" entities are exluded from any query so serializer returns required data only.




回答2:


I had the same problem in symfony 4.3, but I solved it by requiring 'symfony/expression-language'

composer require symfony/expression-language



来源:https://stackoverflow.com/questions/43742033/symfony2-jms-serializer-exclude-entity-if-getdeleted-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!