Sammaron
Sammaron

Reputation: 196

Adding Parameters to FormEvent Listeners in Symfony2

I'm trying to pass some extra parameters to my FormEvent Listener, which typically just takes one argument, the actual event itself. I tried doing something like:

$builder->addEventListener(FormEvents::PRE_SET_DATA,
    function($event, $extraData) {
        //Do stuff
    }
);

However, this returns an error stating that it's missing the second argument for this function. I'm open to any suggestions! Thanks!

Upvotes: 1

Views: 2850

Answers (1)

qooplmao
qooplmao

Reputation: 17759

The event listener closure only has the event passed to it so your $extraData will never get passed to it via the listener.

If you want to use data from elsewhere in the form inside the closure then you need to pass it in the the closure using a use like so..

$extraData = array('some' => 'stuff');

$builder->addEventListener(FormEvents::PRE_SET_DATA,
    function($event) use ($extraData) {
        //Do stuff
    }
);

Edit

Sorry, I copied and pasted your closure last night which included the function($event, $extraData) and then I forgot to remove it. The use statement is all that is needed. The $extraData that is an argument will not be set by the event so will (probably) come out as null, and might even overwrite the one passed in via the use.

Going from the information in this answer (paraphrased) "$extraData is bound when the function is defined and the arguments are bound when the function is called" would lead me to believe that overwrite may probably happen.

Upvotes: 9

Related Questions