[英]How to validate doctrine type “json” with symfony json constraint in a form correctly?
So, I'd like to enter some json into a form for it to be validated by symfonys json constraint:所以,我想在表单中输入一些 json 以供 symfonys json 约束进行验证:
/**
* @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:主要问题是,当我尝试在 ModelTransformer 中只返回 json 字符串时,我得到了这个异常:
Expected argument of type "array or null", "string" given at property path "variantJson".
属性路径“variantJson”中给出的“array or null”、“string”类型的预期参数。
At the " PropertyAccessor "在“ PropertyAccessor ”
And when I want to return as an array, I do the json_decode, and get a different error:当我想作为一个数组返回时,我执行 json_decode,并得到一个不同的错误:
Expected argument of type "string", "array" given
给定“字符串”、“数组”类型的预期参数
At the " JsonValidator ".在“ JsonValidator ”。
My suspection is, both PropertyAccessor and JsonValidator are in serial, and both need different types.我的怀疑是,PropertyAccessor 和 JsonValidator 都是串行的,并且都需要不同的类型。 I must be missing something.
我肯定错过了什么。 Any ideas?
有任何想法吗? Thanks in advance!
提前致谢!
The Doctrine type JSON does indeed expect an array: https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/types.html#json Doctrine 类型 JSON 确实需要一个数组: https://www.doctrine-project.org/projects10/doctrine-dbal/en#json/
This is useful if you have the need for an Array in your code and want to save that data in the database.如果您需要在代码中使用 Array 并希望将该数据保存在数据库中,这将非常有用。 The data gets converted to a JSON string before saving and back to an Array when retrieved.
数据在保存之前转换为 JSON 字符串,并在检索时返回到数组。
If you don't need the array in your PHP code and your end-user is submitting JSON somehow that needs to be validated.如果您的 PHP 代码中不需要该数组,并且您的最终用户以某种方式提交 JSON 需要验证。 You should probably just save it as a (LONG)TEXT.
您可能应该将其保存为(长)文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.