如何在表单中使用 symfony json 约束正确验证学说类型 "json"?
How to validate doctrine type "json" with symfony json constraint in a form correctly?
所以,我想在表单中输入一些 json 以便它被 symfonys json 约束验证:
/**
* @Assert\Json(
* message = "variantJson field: invalid Json."
* )
* @ORM\Column(type="json", nullable=true)
*/
private $variantJson = [];
表格看起来有点像这样:
$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);
}
))
;
主要问题是,当我尝试仅 return ModelTransformer 中的 json 字符串时,出现此异常:
Expected argument of type "array or null", "string" given at property
path "variantJson".
在“PropertyAccessor”
当我想 return 作为数组时,我执行 json_decode,并得到一个不同的错误:
Expected argument of type "string", "array" given
在“JsonValidator”处。
我的怀疑是,PropertyAccessor 和 JsonValidator 是串行的,并且都需要不同的类型。
我肯定错过了什么。有任何想法吗?提前致谢!
Doctrine 类型 JSON 确实需要一个数组:
https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/types.html#json
如果您需要在代码中使用数组并希望将该数据保存在数据库中,这将非常有用。数据在保存前转换为 JSON 字符串,并在检索时返回数组。
如果您的 PHP 代码中不需要数组,并且您的最终用户正以某种方式提交 JSON,则需要进行验证。您可能应该将其保存为 (LONG)TEXT。
所以,我想在表单中输入一些 json 以便它被 symfonys json 约束验证:
/**
* @Assert\Json(
* message = "variantJson field: invalid Json."
* )
* @ORM\Column(type="json", nullable=true)
*/
private $variantJson = [];
表格看起来有点像这样:
$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);
}
))
;
主要问题是,当我尝试仅 return ModelTransformer 中的 json 字符串时,出现此异常:
Expected argument of type "array or null", "string" given at property path "variantJson".
在“PropertyAccessor”
当我想 return 作为数组时,我执行 json_decode,并得到一个不同的错误:
Expected argument of type "string", "array" given
在“JsonValidator”处。
我的怀疑是,PropertyAccessor 和 JsonValidator 是串行的,并且都需要不同的类型。 我肯定错过了什么。有任何想法吗?提前致谢!
Doctrine 类型 JSON 确实需要一个数组: https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/types.html#json
如果您需要在代码中使用数组并希望将该数据保存在数据库中,这将非常有用。数据在保存前转换为 JSON 字符串,并在检索时返回数组。
如果您的 PHP 代码中不需要数组,并且您的最终用户正以某种方式提交 JSON,则需要进行验证。您可能应该将其保存为 (LONG)TEXT。