How to validate doctrine type "json" with symfony json constraint in a form correctly?

Viewed 1941

So, I'd like to enter some json into a form for it to be validated by symfonys json constraint:

/**
 * @Assert\Json(
 *     message = "variantJson field: invalid Json."
 * )
 * @ORM\Column(type="json", nullable=true)
 */
private $variantJson = [];

The form looks kinda like this:

$builder
        ...
        ->add('variantJson', null, ['attr' => $style])
        ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            ...
            }
        })
    ;

    $builder->get('variantJson')
        ->addModelTransformer(new CallbackTransformer(
            function ($jsonToString) {
                // transform the array to a string
                return json_encode($jsonToString);
            },
            function ($stringToJson) {
                // transform the string back to an array
                dump(json_decode($stringToJson, true));
                dump(json_last_error());
                  //1
                  return $stringToJson;
                  //2
                  return json_decode($stringToJson, true);
            }
        ))
    ;

The main problem is, that when I try to only return the json string in the ModelTransformer, I get this exception:

Expected argument of type "array or null", "string" given at property path "variantJson".

At the "PropertyAccessor"

And when I want to return as an array, I do the json_decode, and get a different error:

Expected argument of type "string", "array" given

At the "JsonValidator".

My suspection is, both PropertyAccessor and JsonValidator are in serial, and both need different types. I must be missing something. Any ideas? Thanks in advance!

1 Answers

The Doctrine type JSON does indeed expect an array: https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/types.html#json

This is useful if you have the need for an Array in your code and want to save that data in the database. The data gets converted to a JSON string before saving and back to an Array when retrieved.

If you don't need the array in your PHP code and your end-user is submitting JSON somehow that needs to be validated. You should probably just save it as a (LONG)TEXT.

Related