【问题标题】:Nested Symfony2 Forms: $options['data'] = null in nested form?嵌套 Symfony2 表单:$options['data'] = null 嵌套表单?
【发布时间】:2012-07-17 14:48:51
【问题描述】:

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

我有两个模型:Job 和 JobAttribute。 一个 Job 有很多 JobAttribute,一个 JobAttribute 有一个 Job:

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 字段类型,例如。文本。

因此,当我在 Controller 中调用 JobType 上的 FormBuilder 时,$options['data'] 正确地填充了 JobType 中的 Job-Object。 但是嵌套的 JobAttributeType 的 $options['data'] 并不指向 JobAttribute 对象。它是 NULL。

有什么问题?协会丢到哪里去了?为什么 $options['data'] = NULL 在嵌套形式中? 是否有解决方法以嵌套形式获取动态字段类型(超出 Doctrine)?

提前致谢!

【问题讨论】:

    标签: php symfony symfony-forms


    【解决方案1】:

    您在构建表单时不能依赖$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());
        }
    });
    

    can be found in the cookbook 的文档。

    【讨论】:

    • 嗨,伯恩哈德。需要表单数据的DataTransformer 怎么样?在PRE_SET_DATA 事件中我无能为力,如果options['data'] 在构建过程中没有值,我该如何连接变压器?谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-05-05
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多