Normalize virtual property with API Platform

I’m trying to return a virtual property with API Platform, but the only thing that I can get is the IRI.

I have multiple User, linked to multiple Organization. Those Organization have only one “Owner” (User class).

I want a property named “coach” which return the Owner of the first Organization

The case is a bit more complex but I simplified it.

AppEntityUser

/**
 * @ApiResource(
 *      itemOperations={
 *          "get"={"security"="is_granted('view', object)"},
 *      },
 *      normalizationContext={"groups"={"user", "user:read"}},
 *      denormalizationContext={"groups"={"user", "user:write"}}
 * )
 * @ORMTable(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    protected $id;

    /**
     * @Groups({"user"})
     */
    protected $email;

    /**
     * @ORMColumn(type="string", length=255, nullable=true)
     * @Groups({"user"})
     */
    private $firstName;

    /**
     * @ApiProperty()
     * @Groups({"user"})
     */
    private $coach;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->organizations = new ArrayCollection();
    }

    [...]

    public function getCoach(): ?User
    {
        $coach = null;
        if (count($this->getOrganizations()) > 0) {
            $coach = $this->getOrganizations()->first()->getOwnerUser();
        }

        return $coach;
    }
}

I still getting

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: "/api/users/4"
}

and I would like a proper User like

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: {
       email: xxx;
       firstName: xxx;
    }
 }

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *