A
A
Alexey Verkhovtsev2019-02-07 21:09:25
symfony
Alexey Verkhovtsev, 2019-02-07 21:09:25

How to validate an internal array in Symfony 4 that contains objects?

Hello! Such a request body

{
  "cf_sub_products": [
    {
      "size": "s",
      "cf_product_id": 1,
      "enabled": false,
      "price":  123,
      "sku":  "123"
    },
    {
      "size": "l",
      "cf_product_id": 1,
      "enabled": true,
      "price":  123,
      "sku":  "asd"
    }
  ]
}

while the validation is only
$constraint = new Assert\Collection(
            [
                'fields' => [
                    'cf_sub_products' => [
                        new Assert\NotBlank(),
                        new Assert\Type('array')
                    ]
                ]
            ]
        );
        $violations = $validator->validate($body, $constraint);

But it is necessary to somehow check the keys in these objects, thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-02-07
@seftomsk

If I understand you correctly:

$constraint = new Assert\Collection(
    [
        'fields' => [
            'cf_sub_products' => [
                new Assert\NotBlank(),
                new Assert\Type('array'),
                new Assert\All([
                    new Assert\Collection([
                        'fields' => [
                            "size" => [
                                new Assert\NotBlank(),
                            ],
                            "cf_product_id" => [
                                new Assert\NotBlank(),
                            ],
                            "enabled" => [
                                new Assert\NotBlank(),
                            ],
                            "price" => [
                                new Assert\NotBlank(),
                            ],
                            "sku" => [
                                new Assert\NotBlank(),
                            ],
                        ],
                    ])
                ])
            ]
        ]
    ]
);
$violations = $validator->validate($body, $constraint);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question