8

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

            }

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.

thanks for help

4

3 回答 3

24

虽然最初的问题相当老,但让我把它留在这里,以防其他人遇到需要更改字段的特定选项而不必再次复制所有选项:

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

于 2015-09-16T13:37:31.323 回答
3

你可以做的是覆盖原来的孩子。

$builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function(FormEvent $event) use($input){
            $form = $event->getForm();

            $form->add($this->factory->createNamed('name_to_override', 'choice', null,
                 array("choices" => array("choice"=>"value"))
                ));

        }

它对我有用。

注意:这仅适用于 PHP 5.4,因为$this在 PHP 5.3 中不提供闭包。

于 2013-05-29T00:12:59.057 回答
0

这里有一篇博客文章通过整个动态表单来处理实体关系:http ://aulatic.16mb.com/wordpress/2011/08/symfony2-dynamic-forms-an-event-driven-approach/

Symfony 网站也有这方面的大部分文档,您只需要编写上面博客文章中完成的 ajax 代码和相应的控制器方法:http: //symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

于 2013-04-12T15:15:50.420 回答