Home > OS >  SYMFONY, API PLATFORM how to add edit and show links to the serialized object
SYMFONY, API PLATFORM how to add edit and show links to the serialized object

Time:04-09

I'm working with SYMFONY and API PLATFORM to create REST API.

I have a Project Entity as an API Resource :

class Project
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $reference;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Gedmo\Slug(fields={"reference"})
     */
    private $slug;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;
    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="projects")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    /**
     * @ORM\ManyToOne(targetEntity=Type::class, inversedBy="projects")
     * @ORM\JoinColumn(nullable=false)
     */
    private $type;

    /**
     * @ORM\ManyToOne(targetEntity=Status::class, inversedBy="projects")
     * @ORM\JoinColumn(nullable=false)
     */
    private $status;

With postman i get :

enter image description here

How can i add edit and show route to get a serialized object like this :

"hydra:member": [
        {
           ...
            "status": "/api/statuses/6",
             "edit": "<a href='link_to_edit'>edit</a>", // add a link to edit
              "show": "<a href='link_to_show'>show</a>" // add a link to show
        },

knowing that i don't want to add edit and show to the entity properties or mapped them

Thanks for the help

CodePudding user response:

Technically, you already have your edit and show routes (if you didn't customize them) : you only have to make a PUT or GET request to the value of the @id field of each object.

If you want to add an extra property to your entity, that isn't mapped you can do something like this :

/**
 * @SerializedName("edit_route")
 *
 * @Groups({"projects:read"}))
 *
 * @return string
 */
public function getEditRoute()
{
    return 'your_edit_route';
}

I wouldn't return HTML in this kind of field though, especially if your route is anything else than GET, and apps that use you API might not use HTML, so you're better off returning the simplest value and letting them do their thing with it.

  • Related