gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:00:07 26 4
gpt4 key购买 nike

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

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

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

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

编辑 1:

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

最佳答案

感谢@Cerad .答案其实是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')
);;
}

然后在同一个类中,创建一个与数组中的字符串同名的公共(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 中的普通表单元素一样指定任何有效选项,它将替换前一个,将其放在表单中的相同原始位置。

关于forms - Symfony4 Forms - 如何有条件地禁用表单字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com