I'm trying to map and validate using #[MapRequestPayload]
request payload with nested request data. When I want to map request with just 1 question, everything works fine, but when I switch type of the $question
property in Quiz DTO I get this validation error.
CreateQuizDto.php
class CreateQuizDto
{
#[Assert\NotBlank()]
#[Assert\Length(min: 1, max: 255)]
public string $label;
#[Assert\Type('countable')]
#[Assert\All(new Assert\Type(CreateQuestionDto::class))]
#[Assert\Valid]
public array $questions;
}
CreateQuestionDto.php
class CreateQuestionDto
{
#[Assert\NotBlank()]
#[Assert\Length(min: 1, max: 255)]
public string $label;
}
Controller.php
#[Route('/api', format: 'json')]
class QuizController extends AbstractController
{
#[Route('/quiz', name: 'app_quiz', methods: ['POST'])]
public function index(#[MapRequestPayload] CreateQuizDto $dto): JsonResponse
{
return $this->json([
'dto' => $dto
]);
}
}
Example request body
{
"label": "Example Quiz",
"questions": [
{
"label": "Example Question 1"
},
{
"label": "Example Question 2"
}
]
}
Response error
{
"type": "https://symfony.com/errors/validation",
"title": "Validation Failed",
"status": 422,
"detail": "questions[0]: This value should be of type App\\Dto\\CreateQuestionDto.\nquestions[1]: This value should be of type App\\Dto\\CreateQuestionDto.",
"violations": [
{
"propertyPath": "questions[0]",
"title": "This value should be of type App\\Dto\\CreateQuestionDto.",
"template": "This value should be of type {{ type }}.",
"parameters": {
"{{ value }}": "array",
"{{ type }}": "App\\Dto\\CreateQuestionDto"
},
"type": "urn:uuid:ba785a8c-82cb-4283-967c-3cf342181b40"
},
{
"propertyPath": "questions[1]",
"title": "This value should be of type App\\Dto\\CreateQuestionDto.",
"template": "This value should be of type {{ type }}.",
"parameters": {
"{{ value }}": "array",
"{{ type }}": "App\\Dto\\CreateQuestionDto"
},
"type": "urn:uuid:ba785a8c-82cb-4283-967c-3cf342181b40"
}
],
}