【问题标题】: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
     ] )`

【问题讨论】:

    标签: symfony entity symfony-forms many-to-one


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2019-01-31
      相关资源
      最近更新 更多