Symfony4 Forms - 你如何有条件地禁用表单域?

Dev*_*ime 1 forms symfony4

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

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

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

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

编辑 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?

Dev*_*ime 5

感谢@Cerad。答案其实就是表单事件

在表单类型(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')
        );;
}
Run Code Online (Sandbox Code Playgroud)

然后在同一个类中,创建一个与数组中的字符串同名的公共方法(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,
        ) );

}
Run Code Online (Sandbox Code Playgroud)

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