How can I access $options passed to buildForm() from an event listener in a clean way? Please see below code sample:
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'preSetDataListener']);
}
public function preSetDataListener(FormEvent $event)
{
// how would I access $options from buildFrom here?
}
An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.
Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.
Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.
$event->getForm()->getConfig()->getOptions()
Don't rely on $event->getForm()->getConfig()->getOptions()
. It's not meant to be used by us. I've opened an issue on the Symfony bug tracker with this problem and they told me to inherit variables into the anonymous function instead. See this example.
Pay attention to the use
keyword.
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
// here you can use $options
}
That gets the $options
array from the parent scope and injects it into the event listener function. It's a PHP feature.
Oh, and this means you'll have to either directly pass an anonymous function as an argument to addEventListener()
(as in the example above) or define it inside buildForm()
as a normal variable, like this:
$listener = function (FormEvent $event) use ($options) {
// do something
}
$builder
->addEventListener(FormEvents::PRE_SET_DATA, $listener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With