Reputation: 59
I am building an api in Symfony 5 with ApiPlatform and i'm not able to get the date property through the api for the comments entity subresource. I get publishedAt when I get all the comments but it doesn't work if I get the comments for one specific post. I included publishedAt to the same normalization_context group for subresourceOperations then the others. What I did wrong ?
Comments Entity:
/**
* @ApiResource(
* attributes={
* "order"={"published_at": "DESC"},
* "pagination_client_enabled"=true,
* "pagination_client_items_per_page"=true
* },
* itemOperations={
* "get",
* "put"={
* "access_control"="is_granted('ROLE_EDITOR') or is_granted('ROLE_SUBSCRIBER') and object.getUser() == user"
* }
* },
* collectionOperations={
* "get",
* "post"={
* "access_control"="is_granted('ROLE_SUBSCRIBER')",
* "normalization_context"={
* "groups"={"get-recipes-comments"}
* }
* },
* },
* denormalizationContext={
* "groups"={"post"}
* },
* subresourceOperations={
* "api_recipes_comments_get_subresource"={
* "method"="GET",
* "normalization_context"={
* "groups"={"get-recipes-comments"}
* }
* }
* }
* )
* @ORM\Entity(repositoryClass=CommentsRepository::class)
*/
class Comments implements AuthoredEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @Groups({"get-recipes-comments"})
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity=Users::class, inversedBy="comments")
* @ORM\JoinColumn(nullable=false)
* @Groups({"get-recipes-comments"})
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity=Recipes::class, inversedBy="comments")
* @Groups({"post"})
*/
private $recipe;
/**
* @ORM\Column(type="smallint", nullable=true)
* @Groups({"post", "get-recipes-comments"})
*/
private $rating;
/**
* @ORM\Column(type="text")
* @Groups({"post", "get-recipes-comments"})
*/
private $content;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
* @Groups({"get-recipes-comments"})
*/
private $published_at;
public function __construct()
{
$this->published_at = new \DateTime();
} ...........
Results in api:
{
"@context": "/api/contexts/Comments",
"@id": "/api/recipes/520/comments",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "/api/comments/1341",
"@type": "Comments",
"id": 1341,
"user": {
"@id": "/api/users/61",
"@type": "Users",
"usergroup": "Super Administrator",
"username": "superadmin"
},
"rating": null,
"content": "new comment"
}
],
"hydra:totalItems": 1
}
Upvotes: 0
Views: 167
Reputation: 591
Please use private $publishedAt; instead of private $published_at;
Upvotes: 1