1

Now i have a lot of entities with:

#[ORM\Column(type: 'datetime')]
#[Groups(['article_category:output'])]
/**
 * @Timestampable(on="create")
 */
private \DateTime $createdAt;

public function getCreatedAt(): \DateTime
{
    return $this->createdAt;
}

And i want to put it inside Trait. But each entity has its own normalization group (like 'article_category:output'). How can I make this field always available from the API Platform?

mcwnuq
  • 13
  • 1
  • 3

1 Answers1

2

What we did:

use a group in your trait, e.g. timestampable

trait TimestampableEntity
{
    /**
     * ...
     * @Groups({"timestampable"})
     */
    protected $createdAt;

    ...
}

Then whenever you want to expose the timestamps, add them to your config (you can add multiple groups to an operation)

<?php
/**
 * @ApiResource(
 *     collectionOperations= {
 *          "get" = {
 *              "normalization_context"={"groups"={"appointment:read", "timestampable"}},
 *           },
 *     },
 * )
 */
class Appointment
{
    use TimestampableEntity;



gblock
  • 495
  • 3
  • 13
  • 1
    Thank you very much, for this simple yet effective solution. – mcwnuq Nov 15 '21 at 18:14
  • It's works but this TimestampableEntity is a vendor so composant update erase your code !! – Jérémy Cornut Jul 13 '23 at 09:31
  • @JérémyCornut Of course you need that trait in your repo. You can use the one from the extension as a start and make the necessary changes. In the end it's just two fields with getters/setters. – gblock Jul 13 '23 at 11:18