Skip to content

Instantly share code, notes, and snippets.

@GregoireHebert
Created April 7, 2020 15:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GregoireHebert/bd99e073818fd88180f5e9d3845e38dd to your computer and use it in GitHub Desktop.
Save GregoireHebert/bd99e073818fd88180f5e9d3845e38dd to your computer and use it in GitHub Desktop.
API-Platform calculated fields
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ApiResource(
* collectionOperations={
* "get" = {"normalization_context" = {"groups" = "Greeting:Collection:Get"}},
* }
* )
* @ORM\Entity
*/
class Greeting
{
/**
* @var int The entity Id
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups("Greeting:Collection:Get")
*/
private $id;
private $a = 1;
private $b = 2;
/**
* @var string A nice person
*
* @ORM\Column
* @Groups("Greeting:Collection:Get")
*/
public $name = '';
public function getId(): int
{
return $this->id;
}
/**
* @return int sum
* @Groups("Greeting:Collection:Get") <- MAGIC IS HERE, You can set a group on a method.
*/
public function getSum()
{
return $this->a+$this->b;
}
}
@GregoireHebert
Copy link
Author

You'll get as result, the calculated field.
calculated-field

@GregoireHebert
Copy link
Author

GregoireHebert commented Apr 8, 2020

in YAML

# api/config/api_platform/resources.yaml
App\Entity\Greeting:
    attributes:
        normalization_context:
            groups: ['greeting:collection:get']
# api/config/serialization/Greeting.yaml
App\Entity\Greeting:
    attributes:
        id:
            groups: ['greeting:collection:get']
        name:
            groups: ['greeting:collection:get']
        sum:
            groups: ['greeting:collection:get']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment