Symfony2 Form handleRequest 无法将外部字段的 POST 数据绑定到实体

Symfony2 Form handleRequest fails to bind the POST data of a foreign field to the entity

首先,这是我的数据库设计。

每个故事都与一个项目相关。

-----------     --------------
| project |     | story      |
-----------     --------------
| id      |     | id         |
| name    |     | project_id |
-----------     | name       |
                --------------

项目故事之间的关系使用以下代码定义。

Entity/Project.php

class Project {
     ...

    /**
     * @ORM\OneToMany(targetEntity="Story", mappedBy="project")
     */
    private $stories;
    ...
}

Entity/Story.php

class Story {
    ...
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity="Project", inversedBy="stories")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id", nullable=FALSE)
     */
    private $project;
    ...
}

我的控制器看起来像这样:

/**
 * @Route("/story/create/project/{id}", name="storyCreate")
 */
public function createAction($id, Request $request) {

    /* Get project by id */
    $project = $this->getDoctrine()
        ->getRepository('AppBundle:Project')
        ->find($id);

    /* Create new story instance and set project */
    $story = new Story();
    $story->setProject($project);

    /* Generate the form and handle the request */
    $form = $this->createForm(CreateStoryType::class, $story);
    $form->handleRequest($request);

    /* Form is submitted and valid */
    if($form->isSubmitted() && $form->isValid()) {
        /* Create the objects */
        $em = $this->getDoctrine()->getManager();
        $em->persist($story);
        $em->flush();
    }

    $this->context['form'] = $form->createView();

    return $this->render('project/create.html.twig', $this->context);
}

我还按照本指南创建了一个项目到 ID 转换器。

http://symfony.com/doc/current/cookbook/form/data_transformers.html#about-model-and-view-transformers

现在,在初始加载页面时,一切看起来都很完美。 我看到一个带有 ProjectTitle 输入文本框的表单,其中 Project 字段预填充了 URL.[=23= 中指示的当前项目]

然而,在提交时,Project 字段总是出现 This value should not be blank. 验证错误,即使它不为空。我做对了吗?我什至无法再访问 $story->getProject(),因为它在提交后设置为 null

好的,因为@jbafford 的评论我发现了问题。

我的数据转换器没有在 reverseTransform 方法中返回实体。