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

Mar*_*dré 3 php events symfony symfony-3.3

我目前正在将一个应用程序转换为Symfony 3.3,我对如何实现以下内容感到很头疼.

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

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

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

我试着看看ChoiceType 文档中是否有一个选项,但似乎我必须去参加onPreSetData活动,但即使在那里,我也只能找到如何动态添加字段,而不是现有字段的值.

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

谢谢.

编辑:感谢@matval回答,如果当前值在选项中,则只有缺少要找的东西,所以我们没有重复的值,例如if (!array_key_exists($entity->getResponsible(), $choices)).

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // Some preceding code...

        // onPreSetData
        ->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSet'))
}

/**
 * On pre set event.
 *
 * @param FormEvent $event
 * @throws \Exception
 */
public function onPreSet(FormEvent $event)
{
    // Get entity & form
    $entity = $event->getData();
    $form = $event->getForm();

    // Fill choices with responsibles from the users table
    $choices = $this->fillResponsibles();

    // If the key does not exists in the choices, add it.
    if (!array_key_exists($entity->getResponsible(), $choices)) {
        $choices[$entity->getResponsible()] = $entity->getResponsible();
    }

    $form->add('responsible', ChoiceType::class, [
        'choices' => $choices,
        'placeholder' => '-- Please Select --',
        'label' => 'Responsible',
        'required' => false,
    ]);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

表单事件是正确的方法.它们是制作动态表单的最佳方式.正如您在symfony doc中看到的那样,您应该ResponsiblePRE_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,
    ]);
});
Run Code Online (Sandbox Code Playgroud)

如果要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,
    ]);
});
Run Code Online (Sandbox Code Playgroud)