D. Schreier
D. Schreier

Reputation: 1788

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.

App\Entity\User

/**
 * @ApiResource(
 *      itemOperations={
 *          "get"={"security"="is_granted('view', object)"},
 *      },
 *      normalizationContext={"groups"={"user", "user:read"}},
 *      denormalizationContext={"groups"={"user", "user:write"}}
 * )
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    protected $id;

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

    /**
     * @ORM\Column(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;
    }
 }

Upvotes: 1

Views: 2080

Answers (1)

ultimatum
ultimatum

Reputation: 417

Just function with groups will be enough for Symfony 5

#[Groups(['user:read'])]
public function getCoach(): ?User
{
    $coach = null;
    if (count($this->getOrganizations()) > 0) {
        $coach = $this->getOrganizations()->first()->getOwnerUser();
    }

    return $coach;
}

Upvotes: 1

Related Questions