默认情况下,symfony验证程序违规行为如下所示
[0] => -message: "This value should not be blank."
-propertyPath: "name"
[1] => -message: "This value should not be blank."
-propertyPath: "productVarieties[0].name"
如何将其转换为多维数组,以便将productVarieties [0]嵌套在根数组键中?
我尝试过使用属性访问组件,但似乎属性路径格式错误
foreach ($violations as $violation) {
$this->propertyAccessor->setValue($errors, $violation->getPropertyPath(), $violation->getMessage());
}
异常类: " Symfony的\元器件\ PropertyAccess \异常\ NoSuchPropertyException" 消息:"无法写属性" name"到一个数组。也许你应该 将属性路径写为" [name]"代替"
答案 0 :(得分:1)
问题是您正在尝试将对象属性添加到无法完成的数组中。
根据错误,数组0
的元素productVarieties
本身就是一个数组。它需要是一个为其分配属性的对象。
对于解决方法,您可以首先将其初始化为stdclass对象,如
$this->propertyAccessor->setValue($errors, 'productVarieties[0]', new \stdClass);
或者您可以将productVarieties[0].name
替换为productVarieties[0][name]
。
我还没有和交响乐合作,但它应该会有所帮助。