Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - modify form field with eventListener

Tags:

symfony

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

like image 653
jros Avatar asked Apr 12 '13 08:04

jros


1 Answers

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

like image 106
ivanicus Avatar answered Sep 23 '22 02:09

ivanicus