如果缺少,请将当前对象值添加到ChoiceType值

时间:2018-01-03 19:06:21

标签: php symfony events symfony-3.3

我目前正在将一个应用程序转换为Symfony 3.3,我正在摸索如何实现以下目标。

我有一个ChoiceType字段,名为ResponsibleString个值),从数据库视图中填充。我希望在进入编辑模式时看到Responsible字段已经填充,当记录Responsible值是Responsible字段值的一部分时,这样做。

但是从那时起价值发生了变化,所以当我编辑现有记录时,当值不是已填充的值的一部分时,它将显示为请选择

我的目标是将该缺失值添加到Responsible字段值,以便预先选择,但我还无法找到它。

我试图查看ChoiceType documentation中是否有选项,但似乎我必须去onPreSetData事件这样做,但即使在那里,我只能找到如何动态添加字段,而不是现有字段的值。

任何人都知道如何这样做,哪个是正确的"这样做的方法?

感谢。

修改:感谢@matval回答,如果当前值在选项中,则只会遗漏一些内容,因此我们不会有重复的值,例如{{1} }。

if (!array_key_exists($entity->getResponsible(), $choices))

1 个答案:

答案 0 :(得分:5)

表单事件是正确的方法。它们是制作动态表单的最佳方式。正如您在symfony doc中看到的那样,您应该在Responsible活动期间添加PRE_SET_DATA字段。

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $entity = $event->getData();
    $choices = ... // populate from db
    $choices[] = $entity->getResponsible();
    $form = $event->getForm();    
    $form->add('responsible', ChoiceType::class, [
        'choices' => $choices,
    ]);
});

如果要在表单类型中保留动态字段Responsible(可能重用于创建操作),您仍然可以使用相同的事件。您需要做的就是删除该字段并重新添加。

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $entity = $event->getData();
    $choices = ... // populate from db
    $choices[] = $entity->getResponsible();
    $form = $event->getForm(); 
    $form->add('responsible', ChoiceType::class, [
        'choices' => $choices,
    ]);
});