I need help writing the right constraint syntax in annotation form for validating array of objects

I’m using Symfony 5. In my app, I have a react app that posts entity data to the server. Then on the server side, I’ll json_decode the data into an object, then validate and persist it to the database. I use DTO object instead of the entity class to handle the constraint. The problem came when writing the constraint to handle array of objects.

my data object structure

{
    id: 1,
    name: "john",
    images: [
      { id: 1,   img_name: "hello" },
      { id: 2,   img_name: "world" }
    ]
}

DTO file

class PersonDTO {

    /**
     * @AssertNotBlank
     * @AssertType("integer")
     */
    public $id    

    /**
     * @AssertAll({
     *     @AssertCollection(
     *         fields = {
     *             "id" = @AssertType("integer")
     *         }
     */
    public $images
}

controller

public function index(Request $request, ValidatorInterface $validator) 
{
    $jsonData = $request->getContent();
    $dataObject = json_decode($jsonData);

    $personDTO = new PersonDTO();
    $personDTO->id = $dataObject->id;
    $personDTO->images = $dataObject->images

    $errors = $validator->validate($personDTO);
}

I have followed the Symfony documentation on handling the array of object, but it doesn’t work. The validation failed on the images array with the message Object(AppDTOPersonDTO).images[0]: This value should be of type array|(Traversable&ArrayAccess).

What did I do wrong?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *