0

I build an API with Symfony, so I create a CRUD for an entity, and I import Nelmio Api Doc Bundle for generate a doc with Swagger.

I build POST action with a form, and in the request body, I need to add products relation to the cart I create. So this is the body request I got in my Swagger documentation.

{
  "datetime": "2023-02-03T12:54:05.661Z",
  "customer": {},
  "products": [
    {
      "id": 0
    }
  ]
}

But this body don't work, only this format is accepted :

"products": [
    2, 4
]

Or this one :

"products": {
    "a": 2,
    "b": 4
}

Can you help me to find the good configuration in my form, for my form can accept the JSON body format :

"products": [
    {
      "id": 0
    }
  ]

Cart.php

#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;

#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $datetime = null;

#[ORM\OneToOne(cascade: ['persist', 'remove'])]
private Customer $customer;

#[ORM\ManyToMany(targetEntity: Product::class)]
private ?Collection $products = null;

(getters and setters...)

CartType.php

->add('products', EntityType::class, [
            'class' => Product::class,
            'multiple' => true,
            'constraints' => [
                new NotNull(),
            ],
        ])

CartController.php

#[Route('/api/v1/customer/cart', name: 'cart_create', methods: ['POST'])]
public function createAction(EntityManagerInterface $em, Request $request): Response
{
    $form = $this->buildForm(CartType::class);

    $form->handleRequest($request);

    if (!$form->isSubmitted() || !$form->isValid()) {

        return $this->respond($form, Response::HTTP_BAD_REQUEST);
    }
    
    /** @var Cart $cart */
    $cart = $form->getData();

    $em->persist($cart);
    $em->flush();

    return $this->respond($cart);
}

0 Answers0