Symfony4 Forms - 如何有条件地禁用表单字段?

Symfony4 Forms - How do you conditionally disable a form field?

那么让表单一遍又一遍有效地呈现相同表单的最佳方式是什么,并根据实体的 属性 值有条件地禁用字段?

我有一个发票实体,需要一个用于创建发票的表单,以及在发票流程的各个阶段(生成、发送、支付等)禁用各个字段的同一个表单。

我认为最简单的答案是通过 form_row 选项在 twig 模板中动态禁用它们,但这肯定会影响表单的服务器端验证,因为它不知道该字段已被禁用?

根据数据库中的值禁用字段的最佳方法是什么?

编辑 1:

将问题从 Dynamically disable a field in the twig template or seperate class for each form? 更改为 Symfony4 Forms - How do you conditionally disable a form field?

感谢. The answer is in fact Form Events

在表单类型中(对我来说App\Form\InvoicesType),在构建器的末尾添加一个方法调用:

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $plus_thirty_days = new \DateTime('+28 days');

    $builder
        ->add('client', EntityType::class, array(
            'class' => Clients::class,
            'choice_label' => 'name',
            'disabled' => false,
        ) )
        // the event that will handle the conditional field
        ->addEventListener(
            FormEvents::PRE_SET_DATA,
            array($this, 'onPreSetData')
        );;
}

然后在同一个 class 中,创建一个与数组中的字符串同名的 public 方法(本例为 onPreSetData):

public function onPreSetData(FormEvent $event)
{

    // get the form
    $form = $event->getForm();

    // get the data if 'reviewing' the information
    /**
     * @var Invoices
     */
    $data = $event->getData();


    // disable field if it has been populated with a client already
    if ( $data->getClient() instanceof Clients )
        $form->add('client', EntityType::class, array(
            'class' => Clients::class,
            'choice_label' => 'name',
            'disabled' => true,
        ) );

}

从这里您可以将字段更新为任何有效的 FormType 并指定任何有效的选项,就像您在 From Builder 中的普通表单元素一样,它将替换前一个,并将其放在相同的位置表格中的原始位置。