嵌套的Symfony2 Forms:$options[';data';]在嵌套形式中为null


Nested Symfony2 Forms: $options['data'] = null in nested form?

由于围绕这个主题的文档有些单薄,我走到了死胡同。

我有两个模型:Job和JobAttribute。一个作业有许多作业属性,而一个作业属性有一个作业:

class Job {
    /**
     * @ORM'OneToMany(targetEntity="JobAttribute", mappedBy="job_attributes")
     *
     * @var ArrayCollection
     */
    private $attributes;
}
class JobAttribute {
    /**
    * @ORM'Column(name="type", type="string", length=50)
    * 
    * @var string
    */
    private $type;
    /**
    * @ORM'ManyToOne(targetEntity="Job", inversedBy="jobs")
    */
    private $job;

现在,我有以下FormClass:

class JobType extends AbstractType {
    public function buildForm(FormBuilder $f, array $options) {
        $f->add('name', 'text');
        $f->add('attributes', 'collection', array('type' => new JobAttributeType()));
    }
    public function getName() {
        return 'job';
    }
}
class JobAttributeType extends AbstractType {
    public function buildForm(FormBuilder $f, array $options) {
        $attribute = $options['data'];
        $f->add('value', $attribute->getType());
    }
    public function getDefaultOptions(array $options) {
        return array('data_class' => 'JWF'WorkflowBundle'Entity'JobAttribute');
    }
    public function getName() {
        return 'job_attribute';
    }
}

的确,JobAttribute的type属性包含Form字段类型,例如text。

因此,当我在控制器中调用JobType上的FormBuilder时,$options['data']正确地填充了JobType中的作业对象。但是嵌套的JobAttributeType的$options['data']没有指向JobAttribute对象。它是空的。

怎么了?联想在哪里消失了?为什么$options['data']=NULL在嵌套形式中?是否有一种变通方法可以使动态字段类型(脱离条令)处于嵌套形式?

提前感谢!

在构建表单时不能依赖$options['data'],因为数据在构建后随时都可以(也将)更改。您应该使用事件侦听器。

$formFactory = $builder->getFormFactory();
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formFactory) {
    $form = $event->getForm();
    $data = $event->getData();
    if ($data instanceof JobAttribute) {
        $form->add($formFactory->createNamed('value', $data->getType());
    }
});

这方面的文档可以在食谱中找到。