Symfony2 - modify form field with eventListener

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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

回答1:

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,             ]         )     ); });

Source: https://github.com/symfony/symfony/issues/8513#issuecomment-21868035



回答2:

What you can do is override the original child.

$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"))                 ));          }

It worked for me.

NOTE: this will only work in PHP 5.4, as $this in a Closure is not available in PHP 5.3.



回答3:

There is a blog post here that works through an entire dynamic form for an entity relationship: http://aulatic.16mb.com/wordpress/2011/08/symfony2-dynamic-forms-an-event-driven-approach/

The Symfony site has this mostly documented too, you just need to write the ajax code and corresponding controller method which is done in the blog post above: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!