symfonyapi-platform.comstofdoctrineextensions

How to use Timestampable in a Trait with Platform API groups


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?


Solution

  • 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;