Symfony 2实体字段类型在编辑操作中没有选择现有数据


Symfony 2 Entity Field Type not selecting existing data in edit action

我有一个实体字段类型,我在"编辑"表单中使用。

字段类型列出正确的选项,数据继续存在,但默认情况下它选择列表中的'top'结果,而不是DB中的数据。

因此,例如,如果我有一个记录,shelf标记为SH6,我去编辑,在实体字段类型中选择的默认shelf将是列表顶部的任何内容,即SH1

这意味着用户可能会去编辑unitsInStock并意外地更改shelf的值,因为他们没有意识到它被设置为错误的东西。更令人恼火的是,即使您知道这个问题,您也可能不记得应该设置的值。

这是我的控制器动作。

public function editAction($id, Request $request) {
    $em = $this->getDoctrine()->getManager();
    $article20000stock = $em->getRepository('RegenerysQMSBundle:Article20000Stock')->find($id);
    if (!$article20000stock) {
      throw $this->createNotFoundException(
              'No id ' . $id
      );
    }
     $form = $this->createFormBuilder($article20000stock)
        ->add('article20000Information')
        ->add('unitsInStock')
        ->add('expiryDate')
        ->add('shelf', 'entity', array('class' => 'RegenerysQMSBundle:Shelf', 'property' => 'id', ))
        ->add('submit', 'submit')
        ->getForm();
    $form->handleRequest($request);
    if ($form->isValid()) {
       $em->flush();
     return $this->redirectToRoute('regenerys_qms_article20000stock_individual', array('id' => $id));
}
    $build['form'] = $form->createView();
    return $this->render('forms/editArticle20000Stock.html.twig', $build);
 }

所以实体缺乏关系,这就是导致问题的原因。