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

标签 php symfony events symfony-3.3

我目前正在将应用程序转换为 Symfony 3.3,我正在绞尽脑汁想知道如何才能实现以下目标。

我有一个 ChoiceType 字段,称为 Responsible(String 值),它是从数据库 View 中填充的。我希望在进入编辑模式时看到 Responsible 字段已经填充,当记录 Responsible 值是 Responsible 的一部分时字段值。

但此后值发生了变化,因此当我开始编辑现有记录时,当该值不属于已填充值的一部分时,它将显示为请选择

我的目标是将该缺失值添加到 Responsible 字段值中,以便它被预选,但我还没有找到方法。

我试图查看 ChoiceType 中是否有选项 documentation , 但似乎我必须去 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,
    ]);
}

最佳答案

表单事件是正确的方法。它们是制作动态表单的最佳方式。正如您在 symfony doc 中看到的那样您应该在 PRE_SET_DATA 事件期间添加您的 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,
    ]);
});

如果您想在您的表单类型中保留动态字段 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,
    ]);
});

关于php - 如果缺少,将当前对象值添加到 ChoiceType 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083639/

相关文章:

php - 如何在函数内使用 PDO 计算特定行数?

php - MySQL/PHP 优化 - 基于客户数据的积分

php - 合并两个带有数字键的数组作为关联数组的值以插入MySQL中的多行

mysql - Doctrine一对多关联: Issues with composite primary key

javascript - 如何向jsf标签graphicImage添加多个事件

c# - 将委托(delegate)传递给事件 c#

c++ - MFC 串行通信

javascript - 将大型 JSON 文件从 javascript 发送到 php 的好方法是什么?

php - 如何在 Symfony 中手动调度 Doctrine/Kernel 事件?

php - 在 Windows 上安装 Symfony 2