php - How to add an Event Listener to a dynamically added field using Symfony Forms -
i using event listeners dynamically modify form. want add event listener field added dynamically. im not sure how accomplish this.
public function buildform(formbuilderinterface $builder, array $options) { $builder->add('first_field','choice',array( 'choices'=>array('1'=>'first choice','2'=>'second choice') )); $builder->addeventlistener(formevents::pre_set_data, array($this, 'presetdata')); $builder->get('first_field')->addeventlistener(formevents::post_submit, array($this, 'postsubmit')); } public function presetdata(formevent $event) { $form = $event->getform(); $form->add('second_field','choice',array( 'choices'=>array('1'=>'first choice','2'=>'second choice') )); //some how add event listener field } public function postsubmit(formevent $event) { $form = $event->getform()->getparent(); $form->add('second_field','choice',array( 'choices'=>array('1'=>'first choice','2'=>'second choice') )); //some how add event listener field }
i have trie using $builder
in buildform
function add event listener second_field
because field doesnt exist when form generated throws error.
if try , add new event listener inside first event listener doing:
$form->get('second_field')->addeventlistener(...)
then error:
call undefined method symfony\component\form\form::addeventlistener()
any suggestions welcome.
if, actually.
forminterface does't have addeventlistener method, formbuilderintreface have it. if want add listener, should create form field form builder.
for example:
// create builder field $builder = $form->getconfig()->getformfactory()->createnamedbuilder($name, $type, null, array( /** options **/ 'auto_initialize'=>false // it's important!!! )); // can add listener $builder->addeventlistener(formevents::post_submit, $yourcallbackhere) // , can add field form $form->add($builder->getform());
Comments
Post a Comment