Symfony5 JMS Serializer – model with calculated property without ORM annotation

I have model properties like this:

/**
 * @ORMEntity(repositoryClass=AssignmentRepository::class)
 */
class Assignment
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    private ?int $id;
    
        /**
     * @ORMColumn(type="float", nullable=true)
     */
    private ?float $sale;

    /**
     * @ORMColumn(type="float", nullable=true)
     */
    private ?float $cost;

    /**
     * @JMSType("integer")
     */
    private ?float $marge = null;

    .... 

    
    public function getSale(): ?float
    {
        return $this->sale;
    }

    public function setSale(?float $sale): self
    {
        $this->sale = $sale;

        return $this;
    }

    public function getCost(): ?float
    {
        return $this->cost;
    }

    public function setCost(?float $cost): self
    {
        $this->cost = $cost;

        return $this;
    }
    
    public function getMarge(): ?float
    {
        return $this->getSale() - $this->getCost();
    }

As you can see, $this->sale and $this->cost are ORM properties which are saved in my database.
$this->marge is a non mapped property and is determined by the difference between rates and costs.

But when I get this with a controller and serialize it with JMS serializer the $this->marge property is not present. The key "marge" is not there.

Get this with serializer like this:

$result = $this->assignmentRepository->findAll();

return new JsonResponse(
    $serializer->serialize($result, JsonEncoder::FORMAT),
    Response::HTTP_OK,
    [],
    true
);

When I debug like this:

dump($this->assignmentRepository->find(1));

I got the object with property "marge" = null (although sale is 500 and cost is 400 – expect 100).
When I try to get explicit:

dump($this->assignmentRepository->find(1)->getMarge());

I get a value of "100". Why? I need the value of "marge" without call explicitely like this:

$this->assignmentRepository->find(1);

Question:

How can I get the whole object information with all properties like "sale", "cost" AND a valid calculated value of "marge" (non mapped doctrine entity and difference between sale and cost)?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *