【问题标题】:CollectionType expected argument of type "string or null", "array" given at property path "cc"属性路径“cc”中给出的“字符串或空”、“数组”类型的 CollectionType 预期参数
【发布时间】:2019-07-07 02:39:44
【问题描述】:

有人可以解释为什么我会收到此错误吗?我第一次使用CollectionType。使用documentation。 这是我尝试使用CollectionType的部分:

$builder->add('cc', CollectionType::class, [
         'required' => false,
         'entry_type' => EmailType::class
])

这是我的要求:

{
    "email" => "test@test.com",
    "description" => "test description",
    "subject" => "test",
    "cc" => array:1 [
         0 => "test1@test.com"
    ]
}

【问题讨论】:

  • 您是否将其映射到模型,即来自 PHP 类的表单的结果?如果是这样,您也可以发布代码吗?
  • 不,我只是尝试使用 formbuilder 提交 api 请求。实际上我检查它是否有效。 bu没有任何成功。请求错了吗?但是当我将请求更新为 "cc" => "some string" 验证返回 value is not valid @dbrumann

标签: php symfony symfony-forms symfony4


【解决方案1】:

所以我的问题在于EmailEntity,其中cc 是字符串。我已经使用Data Transformers 来解决这个问题。刚刚补充:

$builder->get('cc')
        ->addModelTransformer(new CallbackTransformer(
            function ($array) {
                return $array;
            },
            function ($array) {
                return json_encode($array);
            }
));

别忘了加use Symfony\Component\Form\CallbackTransformer;

【讨论】:

    【解决方案2】:

    我遇到了和你差不多的问题,但你的确切解决方案对我不起作用,但你让我走上了解决它的道路,因此当然给了你 +1。我想写这个作为评论,但是太长了。这是我必须更改您的解决方案才能使其正常工作的内容:

    $builder->get('myCollection')
        ->addModelTransformer(new CallbackTransformer(
            function ($array) {
                return $array;
            },
            function ($array) {
                $res = array();
                foreach($array as $item) {
                    if ($item === null) {
                        $item = '';
                    }
                    $res[] = $item;
                }
    
                return $res;
            }
        ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多