Skip to content

Commit 29d5610

Browse files
Add calculated field (#1092)
1 parent 0310882 commit 29d5610

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

core/serialization.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,68 @@ This avoids the need for extra queries to be executed when serializing the relat
306306

307307
Instead of embedding relations in the main HTTP response, you may want [to "push" them to the client using HTTP/2 server push](push-relations.md).
308308

309+
### Calculated Field
310+
311+
Sometimes you need to expose calculated fields. This can be done by leveraging the groups. This time not on a property, but on a method.
312+
313+
```php
314+
<?php
315+
316+
declare(strict_types=1);
317+
318+
namespace App\Entity;
319+
320+
use ApiPlatform\Core\Annotation\ApiResource;
321+
use Doctrine\ORM\Mapping as ORM;
322+
use Symfony\Component\Serializer\Annotation\Groups;
323+
324+
/**
325+
* @ApiResource(
326+
* collectionOperations={
327+
* "get"={"normalization_context"={"groups"="greeting:collection:get"}},
328+
* }
329+
* )
330+
* @ORM\Entity
331+
*/
332+
class Greeting
333+
{
334+
/**
335+
* @var int The entity Id
336+
*
337+
* @ORM\Id
338+
* @ORM\GeneratedValue
339+
* @ORM\Column(type="integer")
340+
* @Groups("greeting:collection:get")
341+
*/
342+
private $id;
343+
344+
private $a = 1;
345+
346+
private $b = 2;
347+
348+
/**
349+
* @var string A nice person
350+
*
351+
* @ORM\Column
352+
* @Groups("greeting:collection:get")
353+
*/
354+
public $name = '';
355+
356+
public function getId(): int
357+
{
358+
return $this->id;
359+
}
360+
361+
/**
362+
* @Groups("greeting:collection:get") <- MAGIC IS HERE, you can set a group on a method.
363+
*/
364+
public function getSum(): int
365+
{
366+
return $this->a + $this->b;
367+
}
368+
}
369+
```
370+
309371
### Denormalization
310372

311373
It is also possible to embed a relation in `PUT` and `POST` requests. To enable that feature, set the serialization groups

0 commit comments

Comments
 (0)