Symfony2 - 使用 eventListener 修改表单字段 [英] Symfony2 - modify form field with eventListener
问题描述
我想寻求帮助.我有一个带有下拉列表的表单,我需要根据外部输入修改选项.我想它应该与 eventListener 配合使用
I would like as for help. I have a form with dropdown list and I need to modify choices based on external input. I guess it should work well with eventListener
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use($input){
$form = $event->getForm();
// get existin form child
// modify list of choices
}
我看到的所有示例都是使用 FormEvents 添加新字段,但我需要修改现有字段但我不知道如何访问它.
All samples I have seen are using FormEvents only to add new field, but I need to modify existing field but I don't know how to access it.
感谢帮助
推荐答案
虽然最初的问题已经很老了,但让我把它留在这里,以防其他人遇到需要更改字段的特定选项而不必复制的情况再次所有选项:
While the original question is rather old, let me leave this here in case someone else comes across the need of altering a specific option of a field without having to replicate all options again:
<?php
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
// Get configuration & options of specific field
$config = $form->get('field_to_update')->getConfig();
$options = $config->getOptions();
$form->add(
// Replace original field...
'field_to_update',
$config->getType()->getName(),
// while keeping the original options...
array_replace(
$options,
[
// replacing specific ones
'required' => false,
]
)
);
});
来源:https://github.com/symfony/symfony/issues/8513#issuecomment-21868035
这篇关于Symfony2 - 使用 eventListener 修改表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!