问题
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