首页 > 解决方案 > Symfony 5.2 EntityType 值对 JSON 对象无效

问题描述

我们使用 Symfony 5.2 作为 Angular 项目的 REST-API,并且在定义 EntityTypes 时无法让 Forms 正常工作:

尝试发送 JSON 对象时出现以下错误:

professionBranch:
ERROR: This value is not valid.

我们的表格:

   public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('professionBranch', EntityType::class, [
                'class' => ProfessionBranch::class
            ])
        ;
    }

我们的请求对象:

{
  "idProfession": 1,
  "name": "test",
  "professionBranch": {
    "idProfessionBranch": 1,
    "name": "Heilmittel"
  }
}

当仅提交 ProfessionBranch 的 id 时,表单会识别该实体并且它可以工作。有没有办法告诉 symfony 在“professionBranch”对象中搜索“idProfessionBranch”键,因为我们不想在前端更改整个表单。

  "professionBranch": {
    "idProfessionBranch": 1,
    "name": "Heilmittel"
  }

编辑:这是我使用数据转换器的尝试

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('professionBranch', EntityType::class, [
                'class' => ProfessionBranch::class,
            ]);

        $builder->get('professionBranch')
            ->addModelTransformer($this);

    }

    public function transform($value)
    {
        return $value->getIdProfessionBranch();
    }

    public function reverseTransform($value)
    {
    }

使用数据转换器返回 ID 时显示以下错误消息:

Argument 1 passed to Symfony\\Bridge\\Doctrine\\Form\\ChoiceList\\IdReader::getIdValue() must be an object or null, int give

标签: phpsymfony

解决方案


推荐阅读