Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMSerializer exclude entity by property condition

I have a symfony application with JMSSerializerBundle installed.
My Entity looks like this:

class MyEntity {

    /**
     * Attribute[]
     *
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Attribute", mappedBy="myEntity")
     * @JMS\Groups({"attributeSet_detail"})
     * @ORM\OrderBy({"position" = "ASC"})
     */
    protected $attributes;
}

The AppBundle\Entity\Attribute Entity has a boolean property isActive

Now I want to serialize the MyEntity (including all attributes) BUT only those which property isActive is set to true

like image 719
Sascha Avatar asked May 01 '26 04:05

Sascha


1 Answers

You can use JMS Serializer Dynamic exclusion strategy.

<?php

class MyObject
{

    /**
     * @Exclude(if="true")
     */
    private $name;

    /**
     * @Expose(if="true")
     */
    private $name2;
}

Have a look at the documentation here: https://jmsyst.com/libs/serializer/master/cookbook/exclusion_strategies

like image 84
Shaun Avatar answered May 03 '26 04:05

Shaun