Symfony 表单中的多个对象

Multiple Objects in a Symfony Form

我正在尝试构建一个表格,请求您当前的工作和以前的工作,对象看起来像这样

class Employment {

    private $id;
    private $employerName;
    private $jobTitle;

    //this is a relationship to the class below
    private $address;
    private $phone;
}

class Address {

   private $city;
   private $state;
   private $zip;
}

地址在 Employment 对象中。

我可以构建这样的表单

$builder = $this->createFormBuilder($employment);
$builder
    ->add('employerName', 'text')
    ->add(
        $builder->create('address', 'form', array('by_reference' => ?))
            ->add('city', 'text')
            ->add('state', 'text')
    )

但这只能得到当前的雇主。

问题

如何设置将 2 个相同的对象放入 1 个表单中?我不想创建另一种形式,我需要它采用相同的形式。我考虑过创建一个父对象,但是我需要附加 Doctrine 才能使其工作。

有什么想法吗?

根据您对单一表格的评论,我认为您可能有点想多了。您只需要使用数组将两个就业对象传递给一个表单。

$data = array(
    'current'  => new Employment(),
    'previous' => new Employment(),
);
$builder = $this->createFormBuilder($data);
$builder
    ->add('current',  new EmploymentFormType())
    ->add('previous', new EmploymentFormType())
;

答案假定您已经定义了适合重用的 EmploymentFormType。

http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html

通过将数据放入新的 FormType 中解决了这个问题

class EmploymentFormType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
            ->add('current', new CurrentEmploymentFormType(),array(
                'data_class' => 'RLD\AppBundle\Entity\Employment'))
            ->add('previous', new PreviousEmploymentFormType(),array(
                'data_class' => 'RLD\AppBundle\Entity\Employment'))
        ;
    }

    public function getName()
    {
        return 'employment';
    }

}

这种情况不同于大多数 embedded form type its more dynamic and you are really repeating the form. Where this situation is calling the same object but the lables are different so two types are acceptable. Cerad was close with his answer but for some reason i was getting errors when trying to put it together as he suggested. I found solution to my issue when coming across an answer here。它仍然有点偏离,但在 Symfony 错误的指导下进行了一些调整,我能够让它工作。使用这种格式,我能够像这样在控制器中构建...

$form = $this->createForm(new EmploymentFormType());

return $this->render('RLDAppBundle:Default:test.html.twig', array(
     'form' => $form->createView(),
));

希望这对其他人有所帮助,因为我没有意识到表单类型可以作为类型输入。你知道的越多!