I have model properties like this:
/**
* @ORM\Entity(repositoryClass=AssignmentRepository::class)
*/
class Assignment
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private ?int $id;
/**
* @ORM\Column(type="float", nullable=true)
*/
private ?float $sale;
/**
* @ORM\Column(type="float", nullable=true)
*/
private ?float $cost;
/**
* @JMS\Type("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)?
Remove the marge
property and add annotations for the getMarge
method
/**
* @JMS\VirtualProperty()
*/
public function getMarge(): float
{
return $this->getSale() - $this->getCost();
}
Also it would be better if you wrap you result in round()
because you use the float type