Symfony 5 表单通知:App\Entity\Epic 类的对象无法转换为 int

Posted

技术标签:

【中文标题】Symfony 5 表单通知:App\\Entity\\Epic 类的对象无法转换为 int【英文标题】:Symfony 5 Form Notice: Object of class App\Entity\Epic could not be converted to intSymfony 5 表单通知:App\Entity\Epic 类的对象无法转换为 int 【发布时间】:2021-07-05 17:21:33 【问题描述】:

如何正确添加带有epic_id的任务?

应此要求

curl -XPOST -H "Content-Type: application/json" -d '"title": "test1","description":"jhgdsh","epic":1' http://localhost: 8080/api/任务/添加

出错了

注意:App\Entity\Epic 类的对象无法转换为 int(500 内部服务器错误)

TaskController.php

<?php

class TaskController extends AbstractApiController

    /**
    * @Route("/create", name="create")
    */
    public function createAction( Request $request ): Response
    
        $form = $this->buildForm( TaskType::class );

        $form->handleRequest($request);

        if( !$form->isSubmitted() || !$form->isValid() )
        
            return $this->respond( $form, Response::HTTP_BAD_REQUEST );
        
        /** @var Task $task */
        $task = $form->getData();

        $this->getDoctrine()->getManager()->persist( $task );
        $this->getDoctrine()->getManager()->flush();

        return $this->respond( $task );
    

Form/TaskType.php

class TaskType extends AbstractType

    public function buildForm(FormBuilderInterface $builder, array $options): void
    
        $builder
            ...
            ->add('epic', EntityType::class,
                [
                    'class' => Epic::class,
                    'choice_label' => 'epic',
                    'constraints' => [
                        new NotNull( [
                            'message' => 'Epic cannot be blank.'
                        ] ),
                        new GreaterThan( [
                            'value' => 0
                        ] )
                    ]
                ]
            );
    

实体/Task.php

/**
* @ORM\Table(name="task")
* @ORM\Entity(repositoryClass="App\Repository\TaskRepository")
*/
class Task

    ....

    /**
    * @var Epic
    *
    * @ORM\ManyToOne(targetEntity="Epic", cascade="all")
    */
    private Epic $epic;
   
    ....


问题在于表单类型的过滤器

   `new GreaterThan( [
       'value' => 0
     ] )`

【问题讨论】:

【参考方案1】:

您好,您需要将toString() 添加到您的 Epic 课程中

public function __toString()  
return (string) $this->//title; 

【讨论】:

以上是关于Symfony 5 表单通知:App\Entity\Epic 类的对象无法转换为 int的主要内容,如果未能解决你的问题,请参考以下文章

Symfony 5 VichUploaderBundler:类“App\Entity\xxx”中方法“setImageFile”中参数“imageFile”的类型提示无效

Symfony 错误:在链配置的命名空间 App\Entity 中找不到类 xxx [重复]

无法确定类“App\Entity\XXXX”中属性“image”的访问类型。 Symfony 4 - EasyAdmin 3.2 - VichUploader

Symfony:必须管理传递给选择字段的“App\Entity\Classement”类型的实体。也许您忘记将其保留在实体管理器中?

Symfony4:实体将repositoryClass设置为“App Entity CommentRepository”,但这不是有效的类

Symfony Security 注销未清除 RememberMe 令牌