有两个操作(新建和编辑)使用相同的表单。表单应创建一个新实体 (MyBundle\Entity\Project) 或编辑现有实体。每个项目可以分配给一个团队(MyBundle\Entity\Team),一个团队可以持有多个项目。
实体/Project.php:
/* ... */
/**
* @var Team
*
* @ORM\ManyToOne(targetEntity="Team", inversedBy="projects")
* @ORM\JoinColumn(name="team", referencedColumnName="id")
*/
private $team;
/* ... */
实体/团队.php:
/* ... */
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Project", mappedBy="team")
* @ORM\OrderBy({"title" = "ASC"})
**/
private $projects;
/* ... */
控制器/ProjectController.php:
public function newAction()
{
$project = new Project();
$form = $this->createForm(
new new ProjectType($project),
array(
'action' => $this->generateUrl('mybundle_project_create'),
)
);
/* ... */
}
public function editAction($id, Request $request)
{
/** @var \Doctrine\ORM\EntityManager $em */
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository('MyBundle:Project')->findOneById($id);
$form = $this->createForm(
new ProjectType($project),
$project,
array(
'action' => $this->generateUrl('mybundle_project_edit', array('id' => $project->getId())),
)
);
表单/ProjectType.php:
private $project;
public function __construct($project = null)
{
$this->project = $project;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
/* ... */
->add('team', 'entity', array(
'class' => MyBundle:Team',
'property' => 'name',
'label' => 'Team',
'query_builder' => function (TeamRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.name', 'ASC');
},
'expanded' => false,
'multiple' => false,
'required' => false
))
->add('save', 'submit');
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'MyBundle\Entity\Project',
)
);
}
/**
* @return string
*/
public function getName()
{
return 'mybundle_project';
}
当我访问编辑表单时,下拉列表会正确显示分配的团队。但是当我尝试创建一个新项目时,它给了我以下错误消息:
表单的视图数据应该是 MyBundle\Entity\Project 类的一个实例,但它是一个 (n) 数组。您可以通过将“data_class”选项设置为 null 或添加将 a(n) 数组转换为 MyBundle\Entity\Project 实例的视图转换器来避免此错误。